Class: ElectionBuddy::Resource
- Inherits:
-
Object
- Object
- ElectionBuddy::Resource
- Defined in:
- lib/election_buddy/resource.rb
Overview
Base class for API resources
Direct Known Subclasses
Instance Method Summary collapse
- #error_messages(status) ⇒ Object private
-
#get_request(url, params = {}, headers = {}, &block) ⇒ Hash
Makes a GET request to the API.
- #handle_response(response) ⇒ Object private
-
#initialize(connection) ⇒ Resource
constructor
A new instance of Resource.
-
#post_request(url, body = {}, headers = {}, &block) ⇒ Hash
Makes a POST request to the API.
- #raise_error(status, formatted_error) ⇒ Object private
Constructor Details
#initialize(connection) ⇒ Resource
Returns a new instance of Resource.
15 16 17 |
# File 'lib/election_buddy/resource.rb', line 15 def initialize(connection) @connection = connection end |
Instance Method Details
#error_messages(status) ⇒ Object (private)
58 59 60 61 62 63 64 65 66 67 68 |
# File 'lib/election_buddy/resource.rb', line 58 def (status) = { 400 => "Malformed request", 401 => "Invalid authentication credentials", 403 => "Unauthorized", 404 => "Resource not found", 429 => "Your request exceeded the API rate limit", 500 => "We were unable to perform the request due to server-side problems" } .fetch(status, "Unexpected status code.") end |
#get_request(url, params = {}, headers = {}, &block) ⇒ Hash
Makes a GET request to the API
25 26 27 |
# File 'lib/election_buddy/resource.rb', line 25 def get_request(url, params = {}, headers = {}, &block) handle_response(@connection.get(url, params, headers, &block)) end |
#handle_response(response) ⇒ Object (private)
41 42 43 44 45 |
# File 'lib/election_buddy/resource.rb', line 41 def handle_response(response) return response.body if response.success? || [422, 423].include?(response.status) raise_error(response.status, ErrorFormatter.format(response.body)) end |
#post_request(url, body = {}, headers = {}, &block) ⇒ Hash
Makes a POST request to the API
35 36 37 |
# File 'lib/election_buddy/resource.rb', line 35 def post_request(url, body = {}, headers = {}, &block) handle_response(@connection.post(url, body, headers, &block)) end |
#raise_error(status, formatted_error) ⇒ Object (private)
47 48 49 50 51 52 53 54 55 56 |
# File 'lib/election_buddy/resource.rb', line 47 def raise_error(status, formatted_error) = (status) = if formatted_error "Error #{status}: #{} - #{formatted_error}." else "Error #{status}: #{}." end raise Error, end |