Sha256: e88a4a5f0c7b6617cea90f09f33ebcb2b45cc6fc2e059bd41a4325df6e4b921f

Contents?: true

Size: 1.91 KB

Versions: 2

Compression:

Stored size: 1.91 KB

Contents

if defined?(EM)
class AsyncConnectionAdapter < HTTParty::ConnectionAdapter

  # convert EventMachine::HttpClient to a Net::HTTPResponse
  class AsyncHTTPResponse < Net::HTTPResponse
    def initialize(client)
      headers = client.response_header
      super headers.http_version, headers.http_status, headers.http_reason
      @body = client.response
      @read = true
      headers.each do |k, v|
        self.add_field k.downcase.gsub('_', '-'), v
      end
    end
  end

  # add a request method to EventMachine::HttpConnection to simulate how Net::HTTP works
  class AsyncHTTPConnection < EventMachine::HttpConnection
    def request(raw_request)
      options = {:head => {}}
      raw_request.each_header do |k, v|
        options[:head][k] = v
      end

      if raw_request.body
        options[:head]['Content-Length'] = raw_request.body.bytesize
        options[:head]['Content-Type'] ||= 'application/x-www-form-urlencoded'
        options[:body] = raw_request.body
      end

      case raw_request
      when Net::HTTP::Get
        AsyncHTTPResponse.new self.get options
      when Net::HTTP::Post
        AsyncHTTPResponse.new self.post options
      when Net::HTTP::Put
        AsyncHTTPResponse.new self.put options
      when Net::HTTP::Delete
        AsyncHTTPResponse.new self.delete options
      when Net::HTTP::Head
        AsyncHTTPResponse.new self.head options
      else
        raise "unknown request type #{raw_request}"
      end
    end
  end

  def initialize(uri, options)
    @uri = uri
    @options = options
  end

  def connection
    AsyncHTTPConnection.new.tap do |c|
      c.connopts = HttpConnectionOptions.new(@uri, @options)
      c.uri = @uri
    end
  end

  def self.call(uri, options)
    if EM.reactor_running?
      self.new(uri, options).connection
    else
      HTTParty::ConnectionAdapter.call uri, options
    end
  end
end

else

class AsyncConnectionAdapter < HTTParty::ConnectionAdapter
end

end

Version data entries

2 entries across 2 versions & 1 rubygems

Version Path
sessionm-resthome-0.8.11 lib/resthome/httparty/async_connection_adapter.rb
sessionm-resthome-0.8.10 lib/resthome/httparty/async_connection_adapter.rb