class Blanket::Wrapper
Attributes
extension[RW]
Attribute accessor for file extension that should be appended to all requests
headers[RW]
Attribute accessor for HTTP Headers that should be applied to all requests
params[RW]
Attribute accessor for params that should be applied to all requests
Public Class Methods
new(base_uri, options={})
click to toggle source
Wraps the base URL for an API @param [String, Symbol] base_uri The root URL of the API you wish to wrap. @param [Hash] options An options hash with global values for :headers, :extension and :params @return [Blanket] The Blanket
object wrapping the API
# File lib/blanket/wrapper.rb, line 42 def initialize(base_uri, options={}) @base_uri = base_uri @uri_parts = [] @headers = options[:headers] || {} @params = options[:params] || {} @extension = options[:extension] end
Private Class Methods
add_action(action)
click to toggle source
@macro [attach] REST action
@method $1() Performs a $1 request on the wrapped URL @param [String, Symbol, Numeric] id The resource identifier to attach to the last part of the request @param [Hash] options An options hash with values for :headers, :extension, :params and :body @return [Blanket::Response, Array] A wrapped Blanket::Response or an Array
# File lib/blanket/wrapper.rb, line 13 def add_action(action) define_method(action) do |id=nil, options={}| request(action, id, options) end end
Private Instance Methods
merged_headers(headers)
click to toggle source
# File lib/blanket/wrapper.rb, line 88 def merged_headers(headers) @headers.merge(headers || {}) end
merged_params(params)
click to toggle source
# File lib/blanket/wrapper.rb, line 92 def merged_params(params) @params.merge(params || {}) end
method_missing(method, *args, &block)
click to toggle source
# File lib/blanket/wrapper.rb, line 52 def method_missing(method, *args, &block) Wrapper.new uri_from_parts([method, args.first]), { headers: @headers, extension: @extension, params: @params } end
request(method, id=nil, options={})
click to toggle source
# File lib/blanket/wrapper.rb, line 60 def request(method, id=nil, options={}) if id.is_a? Hash options = id id = nil end headers = Blanket.stringify_keys merged_headers(options[:headers]) params = merged_params(options[:params]) uri = uri_from_parts([id]) if @extension uri = "#{uri}.#{extension}" end response = HTTParty.public_send(method, uri, { query: params, headers: headers, body: options[:body] }.reject { |_, value| value.nil? || value.empty? }) if response.code < 400 body = (response.respond_to? :body) ? response.body : nil (body.is_a? Array) ? body.map(Response.new) : Response.new(body) else raise Blanket::Exceptions.generate_from_response(response) end end
uri_from_parts(parts)
click to toggle source
# File lib/blanket/wrapper.rb, line 96 def uri_from_parts(parts) File.join @base_uri, *parts.compact.map(&:to_s) end