Skip to content

Instantly share code, notes, and snippets.

@nz
Last active October 27, 2021 11:09
Show Gist options
  • Save nz/2510941 to your computer and use it in GitHub Desktop.
Save nz/2510941 to your computer and use it in GitHub Desktop.
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