Module: Address::Io::ApiResource
- Included in:
- Addresses, Address::Io::ApiOperations::List, City, State
- Defined in:
- lib/address/io/api_resource.rb
Constant Summary collapse
- BASE_URL =
'http://open.nfe.io'
Class Method Summary collapse
Instance Method Summary collapse
- #api_request(url, method, params = nil) ⇒ Object
- #encode(params) ⇒ Object
- #recursive_symbolize_keys(h) ⇒ Object
- #url_encode(key) ⇒ Object
Class Method Details
.included(base) ⇒ Object
54 55 56 |
# File 'lib/address/io/api_resource.rb', line 54 def self.included(base) base.extend(ApiResource) end |
Instance Method Details
#api_request(url, method, params = nil) ⇒ Object
14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 |
# File 'lib/address/io/api_resource.rb', line 14 def api_request(url, method, params = nil) url = URI.parse(self::BASE_URL).merge(url).to_s api_key = Address::Io.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 return e.http_body rescue RestClient::Exception => e raise e end response = JSON.parse(response.to_str) recursive_symbolize_keys response end |
#encode(params) ⇒ Object
10 11 12 |
# File 'lib/address/io/api_resource.rb', line 10 def encode(params) params.map { |k,v| "#{k}=#{url_encode(v)}" }.join('&') end |
#recursive_symbolize_keys(h) ⇒ Object
39 40 41 42 43 44 45 46 47 48 49 50 51 52 |
# File 'lib/address/io/api_resource.rb', line 39 def recursive_symbolize_keys(h) case h when Hash Hash[ h.map do |k, v| [ k.respond_to?(:to_sym) ? k.to_sym : k, recursive_symbolize_keys(v) ] end ] when Enumerable h.map { |v| recursive_symbolize_keys(v) } else h end end |
#url_encode(key) ⇒ Object
6 7 8 |
# File 'lib/address/io/api_resource.rb', line 6 def url_encode(key) URI.escape(key.to_s, Regexp.new("[^#{URI::PATTERN::UNRESERVED}]")) end |