public
Last active

Wrapper to RestClient for RESTful JSON APIs, like ElasticSearch. TODO: rebuild with Faraday.

  • Download Gist
http.rb
Ruby
1 2 3 4 5 6 7 8 9 10 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 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96
# A light wrapper around RestClient which centralizes a few things for us:
#
# - Light accessors for the method option.
# - JSON by default. If we need others in the future, maybe submodularize.
# - Plug Rails.logger into RestClient.
# - Rather strict one-second open/data timeout. Perhaps to be tweaked.
 
require 'rest_client'
require 'yajl'
 
module Http
 
if defined?(Rails)
RestClient.log = Object.new.tap do |proxy|
def proxy.<<(msg)
Rails.logger.info(msg)
end
end
end
 
TIMEOUT = 1 # second
 
def self.get(url, options={})
request({ url: url, method: :get }.merge(options))
end
 
def self.delete(url, options={})
request({ url: url, method: :delete }.merge(options))
end
 
def self.post(url, options={})
request({ url: url, method: :post }.merge(options))
end
 
def self.put(url, options={})
request({ url: url, method: :put }.merge(options))
end
 
def self.head(url, options={})
request({ url: url, method: :head }.merge(options))
end
 
def self.request(options={})
options = {
headers: {
accept: :json,
content_type: :json
},
open_timeout: TIMEOUT,
timeout: TIMEOUT
}.merge(options)
 
begin
 
request = RestClient::Request.new(options)
response = request.execute
parse_response(response, options)
 
rescue *Errors::RestClient => e
response = e.try(:response)
Rails.logger.error [e.message, response.try(:to_str)].compact.join(" - ")
parse_response(response, options)
rescue ArgumentError => e
Rails.logger.error "#{e.message} in #{options.inspect}"
blank_response(options)
end
end
 
module Errors
RestClient = [
RestClient::Unauthorized,
RestClient::InternalServerError,
RestClient::BadRequest
]
end
 
 
def self.parse_response(response, options)
case (options[:headers]||{})[:accept]
when :json
JSON.parse(response.to_str)
else
response.to_str
end
end
 
def self.blank_response(options)
case options[:accept]
when :json
{}
else
""
end
end
 
end

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.