Class: HttpCaller::Curb

Inherits:
Object
  • Object
show all
Defined in:
lib/http_caller/curb.rb

Instance Method Summary collapse

Instance Method Details

#call(opts) ⇒ Object



11
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
37
38
39
40
41
42
# File 'lib/http_caller/curb.rb', line 11

def call opts
  accept = HttpCaller::APPLICATION_TYPES[opts.fetch(:accept, :json)]
  content_type = HttpCaller::APPLICATION_TYPES[opts.fetch(:content_type, :json)]

  begin
    case opts[:method]
    when :post
      http = Curl.post(opts[:uri].to_s, opts[:payload]) do |http|
        http.headers['Content-Type'] = content_type
        http.headers['Accept'] = accept
      end
      response(http)
    when :get
      http = Curl.get(opts[:uri].to_s) do |http|
        http.headers['Accept'] = accept
      end
      response(http)
    when :put
      http = Curl.put(opts[:uri].to_s, opts[:payload]) do |http|
        http.headers['Content-Type'] = content_type
        http.headers['Accept'] = accept
      end
      response(http)
    else
      raise ArgumentError.new("Unknown call method: #{opts[:method]}")
    end
  rescue Curl::Err::ConnectionFailedError
    raise Errno::ECONNREFUSED
  rescue Curl::Err::TimeoutError
    raise Errno::ETIMEDOUT
  end
end

#response(http) ⇒ Object



7
8
9
# File 'lib/http_caller/curb.rb', line 7

def response http
  Response.new(http.response_code, http.body_str)
end