Module: Served::Resource::Requestable::ClassMethods
- Defined in:
- lib/served/resource/requestable.rb
Instance Method Summary collapse
- #all(params = {}) ⇒ Object
-
#client ⇒ Served::HTTPClient
The HTTPClient using the configured backend.
-
#find(id, params = {}) ⇒ Resource::Base
Looks up a resource on the service by id.
- #get(id, params = {}) ⇒ Object
-
#handle(code_or_range, symbol_or_proc = nil, &block) ⇒ Object
Sets individual handlers for response codes, accepts a proc or a symbol representing a method.
- #handle_response(response) ⇒ Object
-
#headers(h = {}) ⇒ Object
Defines the default headers that should be used for the request.
Instance Method Details
#all(params = {}) ⇒ Object
124 125 126 |
# File 'lib/served/resource/requestable.rb', line 124 def all(params = {}) get(nil, params).map { |resource| new(resource) } end |
#client ⇒ Served::HTTPClient
Returns the HTTPClient using the configured backend.
129 130 131 |
# File 'lib/served/resource/requestable.rb', line 129 def client @client ||= Served::HTTPClient.new(self) end |
#find(id, params = {}) ⇒ Resource::Base
Looks up a resource on the service by id. For example, ‘SomeResource.find(5)` would call `/some_resources/5`
119 120 121 122 |
# File 'lib/served/resource/requestable.rb', line 119 def find(id, params = {}) instance = new(id: id) instance.reload(params) end |
#get(id, params = {}) ⇒ Object
133 134 135 |
# 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) ⇒ Object
Sets individual handlers for response codes, accepts a proc or a symbol representing a method
93 94 95 96 97 98 99 100 101 102 |
# 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) ⇒ Object
68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 |
# 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 = {}) ⇒ Object
Defines the default headers that should be used for the request.
108 109 110 111 112 |
# File 'lib/served/resource/requestable.rb', line 108 def headers(h = {}) headers ||= _headers _headers(headers.merge!(h)) unless h.empty? _headers end |