Class: Rodent::Listener

Inherits:
Object
  • Object
show all
Defined in:
lib/rodent/listener.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(type, &block) ⇒ Listener

Returns a new instance of Listener.



10
11
12
13
# File 'lib/rodent/listener.rb', line 10

def initialize(type, &block)
  @type = type
  @source = block
end

Instance Attribute Details

#bodyObject

Returns the value of attribute body.



8
9
10
# File 'lib/rodent/listener.rb', line 8

def body
  @body
end

#headersObject

Returns the value of attribute headers.



8
9
10
# File 'lib/rodent/listener.rb', line 8

def headers
  @headers
end

#paramsObject

Returns the value of attribute params.



8
9
10
# File 'lib/rodent/listener.rb', line 8

def params
  @params
end

#statusObject

Returns the value of attribute status.



8
9
10
# File 'lib/rodent/listener.rb', line 8

def status
  @status
end

#typeObject (readonly)

Returns the value of attribute type.



7
8
9
# File 'lib/rodent/listener.rb', line 7

def type
  @type
end

Instance Method Details

#bind(error_handler) ⇒ Object



15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
# File 'lib/rodent/listener.rb', line 15

def bind(error_handler)
  AMQP::Channel.new do |channel|
    channel.prefetch(100)
    queue = channel.queue(@type, exclusive: true, auto_delete: true)
    queue.bind(channel.direct('rodent.requests'), routing_key: @type)
    queue.subscribe(ack: true) do |, payload|
      begin
        self.body = call(MultiJson.load(payload))
      rescue Exception => e
        self.status, self.headers, self.body = error_handler.call(e) if error_handler
      end
      channel.default_exchange.publish(MultiJson.dump(response), routing_key: .reply_to, correlation_id: .message_id)
      .ack
    end
  end
end

#call(params = {}) ⇒ Object



32
33
34
35
36
37
38
39
40
# File 'lib/rodent/listener.rb', line 32

def call(params = {})
  self.params = params
  self.status = 200
  self.headers = {}
  unless respond_to?(method_name)
    define_singleton_method(method_name, @source)
  end
  MultiJson.dump(self.send(method_name))
end

#method_nameObject



42
43
44
# File 'lib/rodent/listener.rb', line 42

def method_name
  ('rodent_' + @type).gsub('.', '_').to_sym
end

#responseObject



46
47
48
# File 'lib/rodent/listener.rb', line 46

def response
  {status: status, headers: headers, body: body}
end