Class: Her::API

Inherits:
Object
  • Object
show all
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`:

Class Method Summary (collapse)

Instance Method Summary (collapse)

Constructor Details

- (API) initialize(*args, &blk)

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

Examples:

Setting up a new API

api = Her::API.new :url => "https://api.example" do |connection|
  connection.use Faraday::Request::UrlEncoded
  connection.use Her::Middleware::DefaultParseJSON
end

class User
  uses_api api
end


26
27
28
# File 'lib/her/api.rb', line 26

def initialize(*args, &blk)
  self.setup(*args, &blk)
end

Class Method Details

+ (Object) setup(opts = {}, &block)

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(opts={}, &block)
  @default_api = new
  @default_api.setup(opts, &block)
end

Instance Method Details

- (Object) setup(opts = {}, &blk)

Setup the API connection.

Examples:

Setting up the default API connection

Her::API.setup :url => "https://api.example"

A custom middleware added to the default list

class MyAuthentication < Faraday::Middleware
  def call(env)
    env[:request_headers]["X-API-Token"] = "bb2b2dd75413d32c1ac421d39e95b978d1819ff611f68fc2fdd5c8b9c7331192"
    @app.call(env)
  end
end
Her::API.setup :url => "https://api.example.com" do |connection|
  connection.use Faraday::Request::UrlEncoded
  connection.use Her::Middleware::DefaultParseJSON
  connection.use MyAuthentication
  connection.use Faraday::Adapter::NetHttp
end

A custom parse middleware

class MyCustomParser < Faraday::Response::Middleware
  def on_complete(env)
    json = JSON.parse(env[:body], :symbolize_names => true)
    errors = json.delete(:errors) || {}
     = json.delete(:metadata) || []
    env[:body] = { :data => json, :errors => errors, :metadata =>  }
  end
end
Her::API.setup :url => "https://api.example.com" do |connection|
  connection.use Faraday::Request::UrlEncoded
  connection.use MyCustomParser
  connection.use Faraday::Adapter::NetHttp
end

Parameters:

  • opts (Hash) (defaults to: {})

    the Faraday options

Options Hash (opts):

Returns:

  • Faraday::Connection



69
70
71
72
73
74
75
76
77
# File 'lib/her/api.rb', line 69

def setup(opts={}, &blk)
  opts[:url] = opts.delete(:base_uri) if opts.include?(:base_uri) # Support legacy :base_uri option
  @base_uri = opts[:url]
  @options = opts
  @connection = Faraday.new(@options) do |connection|
    yield connection if block_given?
  end
  self
end