Skip to content

@nz /http.rb
Last active

Embed URL

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
Wrapper to RestClient for RESTful JSON APIs, like ElasticSearch. TODO: rebuild with Faraday.
# 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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Something went wrong with that request. Please try again.