Class: Fetcher

Inherits:
Object
  • Object
show all
Defined in:
lib/utils/fetcher.rb

Overview

Simple object to handle all data fetching and parsing

Class Method Summary collapse

Class Method Details

.call(endpoint, query = nil) ⇒ Object



4
5
6
7
8
9
# File 'lib/utils/fetcher.rb', line 4

def call(endpoint, query = nil)
  ErrorHandling.undefined_endpoint(endpoint) unless ENDPOINT_OBJECTS[endpoint]

  path = "#{BASE_URI}#{endpoint.to_s.tr('_', '-')}/#{sanitize_query(query)}"
  call_uri(path).merge(resource_name: endpoint)
end

.call_uri(path) ⇒ Object



11
12
13
14
15
# File 'lib/utils/fetcher.rb', line 11

def call_uri(path)
  uri  = URI(path)
  resp = Net::HTTP.get(uri)
  JSON.parse(resp, symbolize_names: true).merge(url: path)
end

.sanitize_query(query) ⇒ Object



17
18
19
20
21
22
23
24
25
26
# File 'lib/utils/fetcher.rb', line 17

def sanitize_query(query)
  return query unless query.is_a? Hash

  query[:limit] ||= 20
  query[:offset] = query[:page] ? query[:limit] * (query[:page] - 1) : (query[:offset] || 0)
  query.reduce('?') do |result, param|
    key, value = param
    result + (key == :page ? '' : "#{key}=#{value}&")
  end.chop
end