class MessageChannel::Druby
Attributes
host[R]
port[R]
Public Class Methods
new( host: nil, port: nil )
click to toggle source
# File lib/message_channel/druby.rb, line 111 def initialize( host: nil, port: nil ) @host = host || "127.0.0.1" @port = ( port || 8787 ).to_i @agent = Agent.new( host: @host, port: @port ) @threads = {} end
Public Instance Methods
listen( *patterns, timeout: nil, &block )
click to toggle source
# File lib/message_channel/druby.rb, line 159 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 )
click to toggle source
# File lib/message_channel/druby.rb, line 144 def listen_each( *patterns, &block ) patterns.each do |pattern| @threads[pattern] = Thread.start( pattern ) do |pttrn| begin @agent.listen_each( pttrn ) do |topic, message| items = JSON.parse( message, symbolize_names: true ) block.call( topic, items ) end rescue => error nil end end end end
listen_once( *patterns )
click to toggle source
# File lib/message_channel/druby.rb, line 118 def listen_once( *patterns ) queue = Queue.new threads = {} patterns.each do |pattern| threads[pattern] = Thread.start( pattern ) do |pttrn| agent = Agent.new begin topic, message = * agent.listen_once( pttrn ) items = JSON.parse( message, symbolize_names: true ) queue.push( [topic, items] ) rescue => error nil end end end topic, items = queue.pop patterns.each do |pattern| threads[pattern].kill rescue nil threads.delete( pattern ) rescue nil end [topic, items] rescue nil end
notify( topic, **items )
click to toggle source
# File lib/message_channel/druby.rb, line 186 def notify( topic, **items ) @agent.notify( topic, items.to_json ) end
unlisten( *patterns )
click to toggle source
# File lib/message_channel/druby.rb, line 179 def unlisten( *patterns ) patterns.each do |pattern| @agent.unlisten( pattern ) @threads.delete( pattern ) end end