Module: Openaq::Networking

Included in:
Client
Defined in:
lib/openaq/networking.rb

Constant Summary collapse

PARAMS =
{}.freeze

Instance Method Summary collapse

Instance Method Details

#get(path, params = PARAMS) ⇒ Object

Raises:



11
12
13
14
15
16
17
18
19
20
21
22
# File 'lib/openaq/networking.rb', line 11

def get(path, params = PARAMS)
  uri             = build_uri(path, params)
  response        = Net::HTTP.get_response(uri)
  parsed_response = JSON.parse(response.body)

  if not response.is_a?(Net::HTTPSuccess)
    err_msg = "#{parsed_response['error']}, #{parsed_response['message']}"
    raise Openaq::Error, err_msg
  end

  parsed_response['results']
end

#paginated_get(path, params = PARAMS) ⇒ Object

Raises:

  • (StopIteration)

    when there are no more results

  • (Openaq::Error)

    if the request is not successful



26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
# File 'lib/openaq/networking.rb', line 26

def paginated_get(path, params = PARAMS)
  Enumerator.new do |yielder|
    page = 1
    params = { page: page }.merge(params)

    loop do
      response = get(path, params)
      if !response.empty?
        response.map { |item| yielder << item }
        params[:page] += 1
      else
        raise StopIteration
      end
    end
  end.lazy
end