Class: MessageChannel::Observer

Inherits:
Object
  • Object
show all
Defined in:
lib/message_channel/observer.rb

Defined Under Namespace

Classes: Agent

Instance Method Summary collapse

Constructor Details

#initialize(**_options) ⇒ Observer

Returns a new instance of Observer.



18
19
20
21
22
23
24
# File 'lib/message_channel/observer.rb', line 18

def initialize( **_options )
  @asyncs  =  {}
  @awaits  =  {}
  @queues  =  {}
  @@Agent  ||=  Agent.new
  @@Agent.add_observer( self, :action ) 
end

Instance Method Details

#action(topic, message) ⇒ Object



26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
# File 'lib/message_channel/observer.rb', line 26

def action( topic, message )
  items  =  JSON.parse( message, symbolize_names: true )
  @asyncs.keys.each do |pattern|
    if File.fnmatch( pattern, topic, File::FNM_PATHNAME )
      if ( action  =  @asyncs[pattern] )
        action.call( topic, items )
      end
    end
  end
  @awaits.keys.each do |queue|
    @awaits[queue].each do |pattern|
      if File.fnmatch( pattern, topic, File::FNM_PATHNAME )
        queue.push( [topic, items] )
      end
    end
  end
end

#listen(*patterns, timeout: nil, &block) ⇒ Object



58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
# File 'lib/message_channel/observer.rb', line 58

def listen( *patterns, timeout: nil, &block )
  if block_given?
    listen_each( *patterns ) do |topic, items|
      block.call( topic, items )
    end
    return  nil
  end
  if timeout.nil? || ( timeout.is_a?( Numeric ) && timeout >= 0 )
    begin
      Timeout.timeout( timeout ) do
        listen_once( *patterns )
      end
    rescue  Timeout::Error
      return  nil
    end
  else
    raise  ArgumentError, "timeout: %s" % timeout
  end
end

#listen_each(*patterns, &block) ⇒ Object



52
53
54
55
56
# File 'lib/message_channel/observer.rb', line 52

def listen_each( *patterns, &block )
  patterns.each do |pattern|
    @asyncs[pattern]  =  block
  end
end

#listen_once(*patterns) ⇒ Object



44
45
46
47
48
49
50
# File 'lib/message_channel/observer.rb', line 44

def listen_once( *patterns )
  queue  =  Queue.new
  @awaits[queue]  =  patterns
  topic, items  =  * queue.pop
  @awaits.delete( queue )    rescue nil
  [topic, items]
end

#notify(topic, **items) ⇒ Object



86
87
88
# File 'lib/message_channel/observer.rb', line 86

def notify( topic, **items )
  @@Agent.notify( topic, items.to_json )
end

#unlisten(*patterns) ⇒ Object



78
79
80
81
82
83
84
# File 'lib/message_channel/observer.rb', line 78

def unlisten( *patterns )
  patterns.each do |pattern|
    if ( action  =  @asyncs[pattern] )
      @asyncs.delete( pattern )
    end
  end
end