Class: FridgeApi::Client

Inherits:
Object
  • Object
show all
Includes:
Options
Defined in:
lib/fridge_api/client.rb

Constant Summary

Constants included from Options

Options::DEFAULTS

Instance Attribute Summary

Attributes included from Options

#access_token, #client_id, #client_secret

Instance Method Summary collapse

Methods included from Options

#api_endpoint, #configure, keys, #reset!

Constructor Details

#initialize(options = {}) ⇒ Client

Returns a new instance of Client.



12
13
14
15
16
17
# File 'lib/fridge_api/client.rb', line 12

def initialize(options = {})
  reset!
  FridgeApi::Options.keys.each do |key|
    instance_variable_set(:"@#{key}", options[key] || instance_variable_get(:"@#{key}"))
  end
end

Instance Method Details

#agentObject



39
40
41
42
43
44
45
46
# File 'lib/fridge_api/client.rb', line 39

def agent
  @agent ||= Sawyer::Agent.new(api_endpoint, {}) do |http|
    http.headers[:content_type] = "application/json"
    if !!@access_token
      http.authorization 'token', @access_token
    end
  end
end

#delete(url, options = {}) ⇒ Object



31
32
33
# File 'lib/fridge_api/client.rb', line 31

def delete(url, options = {})
  request :delete, url, options
end

#get(url, options = {}) ⇒ Object



19
20
21
# File 'lib/fridge_api/client.rb', line 19

def get(url, options = {})
  request :get, url, options
end

#is_fridge_object?(obj) ⇒ Boolean

Returns:

  • (Boolean)


77
78
79
# File 'lib/fridge_api/client.rb', line 77

def is_fridge_object?(obj)
  obj.respond_to?("key?") && (obj.key?(:id) || obj.key?(:uuid))
end

#last_responseObject



35
36
37
# File 'lib/fridge_api/client.rb', line 35

def last_response
  @last_response if defined? @last_response
end

#post(url, options = {}) ⇒ Object



23
24
25
# File 'lib/fridge_api/client.rb', line 23

def post(url, options = {})
  request :post, url, options
end

#put(url, options = {}) ⇒ Object



27
28
29
# File 'lib/fridge_api/client.rb', line 27

def put(url, options = {})
  request :put, url, options
end

#refresh_token!Object



61
62
63
64
65
66
67
68
# File 'lib/fridge_api/client.rb', line 61

def refresh_token!
  res = post("oauth/token", application_authentication)
  if @last_response.status != 200
    raise FridgeApi::Unauthorized
  end
  @access_token = res.access_token
  reset_agent
end

#request(method, path, data, options = {}) ⇒ Object



52
53
54
55
56
57
58
59
# File 'lib/fridge_api/client.rb', line 52

def request(method, path, data, options = {})
  @last_response = res = agent.call(method, URI::Parser.new.escape(path.to_s), data, options)
  if res.status == 401
    refresh_token!
    return request(method, path, data, options)
  end
  parse res.data
end

#reset_agentObject



48
49
50
# File 'lib/fridge_api/client.rb', line 48

def reset_agent
  @agent = nil
end

#to_model(data) ⇒ Object



70
71
72
73
74
75
# File 'lib/fridge_api/client.rb', line 70

def to_model(data)
  if is_fridge_object?(data)
    data = Model.new(data)
  end
  data
end