Sha256: 985f5206f848f8f08f2d263048986d9eaf433cc4505824dfd5d86fc6da91027c

Contents?: true

Size: 1.83 KB

Versions: 1

Compression:

Stored size: 1.83 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[: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

1 entries across 1 versions & 1 rubygems

Version Path
sessionm-resthome-0.8.9 lib/resthome/httparty/async_connection_adapter.rb