Class: Interfacets::Client::Bus

Inherits:
Object
  • Object
show all
Defined in:
lib/interfacets/client/bus.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(id:, channels:, root_url:) ⇒ Bus

Returns a new instance of Bus.



18
19
20
21
22
23
24
25
26
27
28
# File 'lib/interfacets/client/bus.rb', line 18

def initialize(
  id:,
  channels:,
  root_url:
)
  @id = id
  @channels = channels
  @registry = Registry.new
  @channel_index = channels.map { [_1.id, _1] }.to_h
  @root_url = root_url
end

Instance Attribute Details

#channel_index ⇒ Object (readonly)

Returns the value of attribute channel_index.



9
10
11
# File 'lib/interfacets/client/bus.rb', line 9

def channel_index
  @channel_index
end

#channels ⇒ Object (readonly)

Returns the value of attribute channels.



9
10
11
# File 'lib/interfacets/client/bus.rb', line 9

def channels
  @channels
end

#entity ⇒ Object (readonly)

Returns the value of attribute entity.



9
10
11
# File 'lib/interfacets/client/bus.rb', line 9

def entity
  @entity
end

#id ⇒ Object (readonly)

Returns the value of attribute id.



9
10
11
# File 'lib/interfacets/client/bus.rb', line 9

def id
  @id
end

#registry ⇒ Object (readonly)

Returns the value of attribute registry.



9
10
11
# File 'lib/interfacets/client/bus.rb', line 9

def registry
  @registry
end

Instance Method Details

#channel(name) ⇒ Object



39
40
41
# File 'lib/interfacets/client/bus.rb', line 39

def channel(name)
  channel_index.fetch(name.to_s)
end

#handle(event) ⇒ Object



43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
# File 'lib/interfacets/client/bus.rb', line 43

def handle(event)
  channel_id = event.dig("destination", "channel")
  raise("unknown event: #{event.inspect}") unless channel_id
  channel = channel_index.fetch(channel_id)

  channel.handle(
    entity: @entity,
    event: event.fetch("payload"),
    build_entity: ->(name, id) {
      @entity = registry.build(name, id)
      channel_index.values.each { _1.prepare(@entity) }
      @entity
    }
  )

  channel_index.values.each { _1.prepare(entity) }

  entity.class.view.new.render(entity:, channels: channel_index)

  {
    type: "interfacets:bus:render",
    id: id,
    payload: (
      channel_index
        .map { |name, chann| { id: name, payload: chann.result } }
    )
  }
end

#url_for(path) ⇒ Object



30
31
32
33
34
35
36
37
# File 'lib/interfacets/client/bus.rb', line 30

def url_for(path)
  [
    root_url,
    path,
  ]
    .map { _1.sub(%r{/$}, "").sub(%r{^/}, "") }
    .join("/")
end