Class: DripDrop::HTTPClientHandler

Inherits:
BaseHandler show all
Defined in:
lib/dripdrop/handlers/http_client.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Methods inherited from BaseHandler

#handle_error, #on_error, #print_exception

Constructor Details

#initialize(uri, opts = {}) ⇒ HTTPClientHandler

Returns a new instance of HTTPClientHandler.



5
6
7
8
9
10
# File 'lib/dripdrop/handlers/http_client.rb', line 5

def initialize(uri, opts={})
  @uri     = uri
  @address = @uri.to_s
  @opts    = opts
  @message_class = @opts[:message_class] || DripDrop.default_message_class
end

Instance Attribute Details

#addressObject (readonly)

Returns the value of attribute address.



3
4
5
# File 'lib/dripdrop/handlers/http_client.rb', line 3

def address
  @address
end

#optsObject (readonly)

Returns the value of attribute opts.



3
4
5
# File 'lib/dripdrop/handlers/http_client.rb', line 3

def opts
  @opts
end

Instance Method Details

#send_message(message, &block) ⇒ Object



12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
# File 'lib/dripdrop/handlers/http_client.rb', line 12

def send_message(message,&block)
  dd_message = dd_messagify(message)
  if dd_message.is_a?(DripDrop::Message)
    uri_path = @uri.path.empty? ? '/' : @uri.path
    
    req = EM::Protocols::HttpClient.request(
      :host => @uri.host, :port => @uri.port,
      :request => uri_path, :verb => 'POST',
      :contenttype => 'application/json',
      :content => dd_message.encode_json
    )
    req.callback do |response|
      begin
        # Hack to fix evma http
        response[:content] =~ /(\{.*\})/ 
        fixed_body = $1
        block.call(@message_class.decode(fixed_body)) if block
      rescue StandardError => e
        handle_error(e)
      end
    end
  else
    raise "Unsupported message type '#{dd_message.class}'"
  end
end