Instantly share code, notes, and snippets.

Embed
What would you like to do?
class HttpRequestBase
HTTP_VERBS = [:get, :post, :delete, :put].freeze
attr_reader :response, :timeout
def initialize(args={})
@timeout = args[:timeout] || default_timeout
post_initialize(args)
end
# override in child
def base_url
raise NotImplementedError
end
def default_timeout
10
end
# override to modify http object (add headers, etc)
def modify_request(http)
http
end
# post initialize hook
def post_initialize(args)
nil
end
def request(method, path, params)
unless HTTP_VERBS.include?(method)
warn("HTTP method not supported") and return nil
end
url = "#{base_url}#{path}"
@response = Curl.send(method, url, params) do |http|
http.timeout = timeout
modify_request(http)
end
ensure
log(method, url, params)
end
class << self
HTTP_VERBS.each do |action|
define_method(action) do |path, params={}|
new.tap do |obj|
obj.request(action, path, params)
end
end
end
end
private
def log(method, url, params)
status = response ? response.status : "FAILED"
Rails.logger.info("#{status} method=#{method.upcase} #{url} #{params}")
end
end
class GithubRequest < HttpRequestBase
def base_url
'https://api.github.com'
end
def modify_request(http)
http.headers['User-Agent'] = 'Valid Agent'
end
# this could definitely be put into an included module/concern
def json_body(default="{}")
raw = response ? response.body : default
JSON.parse(raw, symbolize_names: true)
end
end
http = GithubRequest.get('/users/ebtoulson')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment