Class: Her::API
- Inherits:
-
Object
- Object
- Her::API
- Defined in:
- lib/her/api.rb
Overview
This class is where all HTTP requests are made. Before using Her, you must configure it so it knows where to make those requests. In Rails, this is usually done in ‘config/initializers/her.rb`:
Instance Attribute Summary collapse
- #base_uri ⇒ Object readonly
- #connection ⇒ Object readonly
- #options ⇒ Object readonly
Class Method Summary collapse
-
.setup(attrs = {}, &block) ⇒ Object
Setup a default API connection.
Instance Method Summary collapse
-
#initialize(*args, &blk) ⇒ API
constructor
Create a new API object.
-
#request(attrs = {}) ⇒ Object
Define a custom parsing procedure.
-
#setup(attrs = {}, &blk) ⇒ Object
Setup the API connection.
Constructor Details
#initialize(*args, &blk) ⇒ API
Create a new API object. This is useful to create multiple APIs and use them with the ‘uses_api` method. If your application uses only one API, you should use Her::API.setup to configure the default API
26 27 28 |
# File 'lib/her/api.rb', line 26 def initialize(*args, &blk) self.setup(*args, &blk) end |
Instance Attribute Details
#base_uri ⇒ Object (readonly)
6 7 8 |
# File 'lib/her/api.rb', line 6 def base_uri @base_uri end |
#connection ⇒ Object (readonly)
6 7 8 |
# File 'lib/her/api.rb', line 6 def connection @connection end |
#options ⇒ Object (readonly)
6 7 8 |
# File 'lib/her/api.rb', line 6 def @options end |
Class Method Details
.setup(attrs = {}, &block) ⇒ Object
Setup a default API connection. Accepted arguments and options are the same as #setup.
9 10 11 12 |
# File 'lib/her/api.rb', line 9 def self.setup(attrs={}, &block) @@default_api = new @@default_api.setup(attrs, &block) end |
Instance Method Details
#request(attrs = {}) ⇒ Object
Define a custom parsing procedure. The procedure is passed the response object and is expected to return a hash with three keys: a main data Hash, an errors Hash and a metadata Hash.
83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 |
# File 'lib/her/api.rb', line 83 def request(attrs={}) method = attrs.delete(:_method) path = attrs.delete(:_path) headers = attrs.delete(:_headers) attrs.delete_if { |key, value| key.to_s =~ /^_/ } # Remove all internal parameters response = @connection.send method do |request| request.headers.merge!(headers) if headers if method == :get # For GET requests, treat additional parameters as querystring data request.url path, attrs else # For POST, PUT and DELETE requests, treat additional parameters as request body request.url path request.body = attrs end end response.env[:body] end |
#setup(attrs = {}, &blk) ⇒ Object
Setup the API connection.
68 69 70 71 72 73 74 75 76 |
# File 'lib/her/api.rb', line 68 def setup(attrs={}, &blk) attrs[:url] = attrs.delete(:base_uri) if attrs.include?(:base_uri) # Support legacy :base_uri option @base_uri = attrs[:url] @options = attrs @connection = Faraday.new(@options) do |connection| yield connection if block_given? end self end |