Sha256: 00420c4b9a1299986dca242651bc4e35dfcf8b42121a916299bb5adc6e6285c1

Contents?: true

Size: 1.45 KB

Versions: 2

Compression:

Stored size: 1.45 KB

Contents

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)
      case raw_request
      when Net::HTTP::Get
        AsyncHTTPResponse.new self.get
      when Net::HTTP::Post
        AsyncHTTPResponse.new self.post
      when Net::HTTP::Put
        AsyncHTTPResponse.new self.put
      when Net::HTTP::Delete
        AsyncHTTPResponse.new self.delete
      when Net::HTTP::Head
        AsyncHTTPResponse.new self.head
      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

Version data entries

2 entries across 2 versions & 1 rubygems

Version Path
sessionm-resthome-0.8.7 lib/resthome/httparty/async_connection_adapter.rb
sessionm-resthome-0.8.6 lib/resthome/httparty/async_connection_adapter.rb