Class: MQ::RPC

Inherits:
BlankSlate show all
Defined in:
lib/mq/rpc.rb

Instance Method Summary collapse

Constructor Details

#initialize(mq, queue, obj = nil) ⇒ RPC

Returns a new instance of RPC.



3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
# File 'lib/mq/rpc.rb', line 3

def initialize mq, queue, obj = nil
  @mq = mq
  @mq.rpcs[queue] ||= self

  if obj
    @obj = case obj
           when ::Class
             obj.new
           when ::Module
             (::Class.new do include(obj) end).new
           else
             obj
           end
    
    @mq.queue(queue).subscribe{ |info, request|
      method, *args = ::Marshal.load(request)
      ret = @obj.__send__(method, *args)

      if info.reply_to
        @mq.queue(info.reply_to).publish(::Marshal.dump(ret), :key => info.reply_to, :message_id => info.message_id)
      end
    }
  else
    @callbacks ||= {}
    # XXX implement and use queue(nil)
    @queue = @mq.queue(@name = "random identifier #{::Kernel.rand(999_999_999_999)}").subscribe{|info, msg|
      if blk = @callbacks.delete(info.message_id)
        blk.call ::Marshal.load(msg)
      end
    }
    @remote = @mq.queue(queue)
  end
end

Dynamic Method Handling

This class handles dynamic methods through the method_missing method

#method_missing(meth, *args, &blk) ⇒ Object



37
38
39
40
41
42
# File 'lib/mq/rpc.rb', line 37

def method_missing meth, *args, &blk
  # XXX use uuids instead
  message_id = "random message id #{::Kernel.rand(999_999_999_999)}"
  @callbacks[message_id] = blk if blk
  @remote.publish(::Marshal.dump([meth, *args]), :reply_to => blk ? @name : nil, :message_id => message_id)
end