Created
March 18, 2014 22:54
-
-
Save doomspork/9631562 to your computer and use it in GitHub Desktop.
Proof-of-concept web service client
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
require 'net/http' | |
require 'json' | |
class Client | |
class << self | |
attr_accessor :host, :port, :api_key, :version | |
end | |
self.host = ENV['ORDERS_API_HOST'] || 'api.orders.com' | |
self.port = ENV['ORDERS_API_PORT'] || 80 | |
self.api_key = ENV['ORDERS_API_KEY'] | |
self.version = ENV['ORDERS_API_VERSION'] | |
def self.search(term, opts = {}) | |
api(:get, '/search', {term: term}.merge(opts)) | |
end | |
def self.add_filter(&block) | |
filters.push(block) | |
end | |
private | |
def self.filters | |
@filters ||= [] | |
end | |
def self.api(method, path, opts = {}) | |
response = remote_request(method, path, opts) | |
# In case (get it?!) we decide to handle individual response types | |
case response | |
when Net::HTTPSuccess | |
body = JSON.parse(response.body) | |
body.respond_to?(:map) ? body.map { |e| filtered(e) } : filtered(body) | |
else | |
nil | |
end | |
end | |
def self.remote_request(method, path, params = {}) | |
params = URI.encode_www_form(params) | |
response = Net::HTTP.start(host, port) do |http| | |
case method | |
when :get | |
http.get("#{path}?#{params}", headers) | |
when :post | |
http.post(path, params, headers) | |
end | |
end | |
end | |
def self.headers | |
{ | |
'accept' => "application/vnd.orders.api.json; version=#{version}", | |
'orders_api_key' => api_key | |
} | |
end | |
def self.filtered(value) | |
filters.inject(value) { |m, f| f.call(m) } | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment