Class: Rcom::Topic

Inherits:
Object
  • Object
show all
Defined in:
lib/rcom/topic.rb

Overview

Implements pub/sub over topics.

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(params) ⇒ Topic

Returns a new instance of Topic.

Parameters:

  • params (Hash)

Options Hash (params):

  • :node (Rcom::Node)
  • :key (String)

    Example: ‘services’



9
10
11
12
# File 'lib/rcom/topic.rb', line 9

def initialize(params)
  @node = params[:node]
  @key = params[:key]
end

Instance Attribute Details

#keyObject (readonly)

Returns the value of attribute key.



4
5
6
# File 'lib/rcom/topic.rb', line 4

def key
  @key
end

#nodeObject (readonly)

Returns the value of attribute node.



4
5
6
# File 'lib/rcom/topic.rb', line 4

def node
  @node
end

Instance Method Details

#publish(message) ⇒ true?

Returns true if it can be published, otherwise nil.

Parameters:

  • message (Hash)

Returns:

  • (true, nil)

    true if it can be published, otherwise nil.



16
17
18
19
20
21
22
23
# File 'lib/rcom/topic.rb', line 16

def publish(message)
  begin
    node.publish(key, message.to_msgpack)
    return true
  rescue
    return nil
  end
end

#subscribe {|message| ... } ⇒ Object

Yield Parameters:

  • message (Hash)

    the message received.



26
27
28
29
30
31
32
33
34
35
36
37
38
39
# File 'lib/rcom/topic.rb', line 26

def subscribe
  begin
    node.subscribe(key) do |on|
      on.message do |channel, message|
        message = MessagePack.unpack(
          message,
          symbolize_keys: true
        )
        yield message
      end
    end
  rescue Interrupt => _
  end
end