Class: Petfinder::Client

Inherits:
Object
  • Object
show all
Includes:
Api
Defined in:
lib/petfinder/client.rb

Instance Method Summary collapse

Methods included from Api

#animal, #animals, #breeds, #organization, #organizations, #type, #types

Constructor Details

#initialize(api_key = Petfinder.api_key, api_secret = Petfinder.api_secret) ⇒ Client

Returns a new instance of Client.

Raises:



6
7
8
9
10
11
12
# File 'lib/petfinder/client.rb', line 6

def initialize(api_key = Petfinder.api_key, api_secret = Petfinder.api_secret)
  @api_key = api_key
  @api_secret = api_secret

  raise Petfinder::Error.new("API key is required") unless @api_key
  raise Petfinder::Error.new("API secret is required") unless @api_secret
end

Instance Method Details

#oauth_clientObject



24
25
26
# File 'lib/petfinder/client.rb', line 24

def oauth_client
  @oauth_client ||= OAuth2::Client.new(@api_key, @api_secret, site: Petfinder::API_URL, token_url: 'oauth2/token')
end

#request(path, params = {}) ⇒ Object



14
15
16
17
18
19
20
21
22
# File 'lib/petfinder/client.rb', line 14

def request(path, params = {})
  response = token.get(path, params: params).parsed

  response

rescue OAuth2::Error => e
  error_data = JSON.parse(e.response.body)
  raise Petfinder::Error.new(error_data), "#{error_data["title"]}: #{error_data["detail"]}"
end

#tokenObject



28
29
30
31
32
# File 'lib/petfinder/client.rb', line 28

def token
  @token = nil if @token&.expired?

  @token ||= oauth_client.client_credentials.get_token
end