Module: Apilayer::ConnectionHelper

Defined in:
lib/apilayer/connection_helper.rb

Instance Method Summary collapse

Instance Method Details

#configsObject



9
10
11
# File 'lib/apilayer/connection_helper.rb', line 9

def configs
  @configs ||= init_configs
end

#configure {|configs| ... } ⇒ Object

Yields:



17
18
19
20
# File 'lib/apilayer/connection_helper.rb', line 17

def configure(&block)
  self.reset_connection
  yield(configs)
end

#connectionObject

Creates a connection for the extended module to an apilayer-service, such as currencylayer and vatlayer. Uses access_key(s) configured with Apilayer module.



25
26
27
28
29
30
# File 'lib/apilayer/connection_helper.rb', line 25

def connection
  @connection ||= ::Faraday.new(
    :url => "#{protocol}://apilayer.net",
    :params => {"access_key" => self.configs[:access_key]}
  )
end

#get_and_parse(url, params = {}) ⇒ Object

Makes a get-request to apilayer’s service and parses the JSON response into a Hash



43
44
45
46
# File 'lib/apilayer/connection_helper.rb', line 43

def get_and_parse(url, params={})
  resp = get_request(url, params)
  parse_response(resp)
end

#get_request(slug, params = {}) ⇒ Object

Makes a get-request to apilayer’s service



50
51
52
53
54
55
56
57
58
# File 'lib/apilayer/connection_helper.rb', line 50

def get_request(slug, params={})
  # calls connection method on the extended module
  connection.get do |req|
    req.url "api/#{slug}"
    params.each_pair do |k,v|
      req.params[k] = v
    end
  end
end

#init_configsObject



4
5
6
7
# File 'lib/apilayer/connection_helper.rb', line 4

def init_configs
  keys = Struct.new(:access_key, :https)
  keys.new
end

#parse_response(resp) ⇒ Object

Parses the JSON response from apilayer into a Hash When errors are returned by apilayer, the ‘info’ and ‘code’ from its error will be used to raise an Apilayer::Error



63
64
65
66
67
68
69
70
71
72
73
# File 'lib/apilayer/connection_helper.rb', line 63

def parse_response(resp)
  body = JSON.parse(resp.body)
  if body['error']
    raise Apilayer::Error.new(
      body['error']['info'],
      body['error']['code']
    )
  else
    body
  end
end

#protocolObject



32
33
34
# File 'lib/apilayer/connection_helper.rb', line 32

def protocol
  self.configs[:https] ? "https" : "http"
end

#reset_configs!Object



13
14
15
# File 'lib/apilayer/connection_helper.rb', line 13

def reset_configs!
  @configs = init_configs
end

#reset_connectionObject

Resets the connection for the extended module. Used when the user needs to re-enter his/her access_key(s)



37
38
39
# File 'lib/apilayer/connection_helper.rb', line 37

def reset_connection
  @connection = nil
end