This repository was archived by the owner on Sep 30, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 14
Expand file tree
/
Copy pathapi_resource.rb
More file actions
51 lines (43 loc) · 1.47 KB
/
api_resource.rb
File metadata and controls
51 lines (43 loc) · 1.47 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
module Nfe
module ApiResource
BASE_URL = 'http://api.nfe.io'
SSL_BUNDLE_PATH = File.dirname(__FILE__) + '/../data/ssl-bundle.crt'
def url_encode(key)
URI.escape(key.to_s, Regexp.new("[^#{URI::PATTERN::UNRESERVED}]"))
end
def encode(params)
params.map { |k,v| "#{k}=#{url_encode(v)}" }.join('&')
end
def api_request(url, method, params=nil)
url = "#{BASE_URL}#{url}"
api_key = Nfe.access_keys
if method == :get && params
params_encoded = encode(params)
url = "#{url}?#{params_encoded}"
params = nil
end
begin
payload = params.to_json
response = RestClient::Request.new(method: method, url: url, payload: payload,
headers: {authorization: api_key,
content_type: 'application/json',
accept: '*/*'}).execute
rescue RestClient::ExceptionWithResponse => e
if rcode = e.http_code and rbody = e.http_body
rbody = JSON.parse(rbody)
rbody = Util.symbolize_names(rbody)
raise NfeError.new(rcode, rbody, rbody, rbody[:message])
else
raise e
end
rescue RestClient::Exception => e
raise e
end
return { } if response == nil || response.empty?
JSON.parse(response)
end
def self.included(base)
base.extend(ApiResource)
end
end
end