module Served::Resource::Requestable::ClassMethods

Public Instance Methods

all(params = {}) click to toggle source
# File lib/served/resource/requestable.rb, line 124
def all(params = {})
  get(nil, params).map { |resource| new(resource) }
end
client() click to toggle source

@return [Served::HTTPClient] the HTTPClient using the configured backend

# File lib/served/resource/requestable.rb, line 129
def client
  @client ||= Served::HTTPClient.new(self)
end
find(id, params = {}) click to toggle source

Looks up a resource on the service by id. For example, `SomeResource.find(5)` would call `/some_resources/5`

@param id [Integer] the id of the resource @return [Resource::Base] the resource object.

# File lib/served/resource/requestable.rb, line 119
def find(id, params = {})
  instance = new(id: id)
  instance.reload(params)
end
get(id, params = {}) click to toggle source
# File lib/served/resource/requestable.rb, line 133
def get(id, params = {})
  handle_response(client.get(resource_name, id, params))
end
handle(code_or_range, symbol_or_proc = nil, &block) click to toggle source

Sets individual handlers for response codes, accepts a proc or a symbol representing a method

@param code [Integer|Range] the response code(s) the handler is to be assigned to @param symbol_or_proc [Symbol|Proc] a symbol representing the method to call, or a proc to be called when

the specific response code has been called. The method or proc should return a hash of attributes, if an
error class is returned it will be raised

@yieldreturn [Hash] a hash of attributes, if an error class is returned it will be raised

# File lib/served/resource/requestable.rb, line 93
def handle(code_or_range, symbol_or_proc = nil, &block)
  raise HandlerRequired unless symbol_or_proc || block_given?
  if code_or_range.is_a?(Range) || code_or_range.is_a?(Array)
    code_or_range.each do |c|
      handlers[c] = symbol_or_proc || block unless handlers.key?(c)
    end
  else
    handlers[code_or_range] = symbol_or_proc || block
  end
end
handle_response(response) click to toggle source
# File lib/served/resource/requestable.rb, line 68
def handle_response(response)
  if raise_on_exceptions
    handler = handlers.fetch(response.code) { proc { HttpError } }
    if handler.is_a? Proc
      result = handler.call(response)
    else
      result = send(handler, response.body)
    end

    if result.respond_to?(:ancestors) && result.ancestors.include?(HttpError)
      raise result.new(response.code, self, response)
    end
    result
  else
    serializer.load(self, response)
  end
end
headers(h = {}) click to toggle source

Defines the default headers that should be used for the request.

@param headers [Hash] the headers to send with each requesat @return headers [Hash] the default headers for the class

# File lib/served/resource/requestable.rb, line 108
def headers(h = {})
  headers ||= _headers
  _headers(headers.merge!(h)) unless h.empty?
  _headers
end