Class: AleAir::FetchJSON

Inherits:
Object
  • Object
show all
Defined in:
lib/ale_air/fetch_json.rb

Overview

Fetches air-quality data from the WAQI (World Air Quality Index) API.

Constant Summary collapse

DEFAULT_BASE_URL =
'https://api.waqi.info'
DEFAULT_OPEN_TIMEOUT =
5
DEFAULT_READ_TIMEOUT =
10

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(secret_token = nil, base_url: DEFAULT_BASE_URL, open_timeout: DEFAULT_OPEN_TIMEOUT, read_timeout: DEFAULT_READ_TIMEOUT) ⇒ FetchJSON

Returns a new instance of FetchJSON.



18
19
20
21
22
23
24
# File 'lib/ale_air/fetch_json.rb', line 18

def initialize(secret_token = nil, base_url: DEFAULT_BASE_URL,
               open_timeout: DEFAULT_OPEN_TIMEOUT, read_timeout: DEFAULT_READ_TIMEOUT)
  @secret_token = secret_token.to_s
  @base_url = base_url
  @open_timeout = open_timeout
  @read_timeout = read_timeout
end

Instance Attribute Details

#danger_levelObject (readonly)

Returns the value of attribute danger_level.



15
16
17
# File 'lib/ale_air/fetch_json.rb', line 15

def danger_level
  @danger_level
end

#descriptive_textObject (readonly)

Returns the value of attribute descriptive_text.



15
16
17
# File 'lib/ale_air/fetch_json.rb', line 15

def descriptive_text
  @descriptive_text
end

#locationObject (readonly)

Returns the value of attribute location.



15
16
17
# File 'lib/ale_air/fetch_json.rb', line 15

def location
  @location
end

#messageObject (readonly)

Returns the value of attribute message.



15
16
17
# File 'lib/ale_air/fetch_json.rb', line 15

def message
  @message
end

#qualityObject (readonly)

Returns the value of attribute quality.



15
16
17
# File 'lib/ale_air/fetch_json.rb', line 15

def quality
  @quality
end

#statusObject (readonly)

Returns the value of attribute status.



15
16
17
# File 'lib/ale_air/fetch_json.rb', line 15

def status
  @status
end

#time_measuredObject (readonly)

Returns the value of attribute time_measured.



15
16
17
# File 'lib/ale_air/fetch_json.rb', line 15

def time_measured
  @time_measured
end

Instance Method Details

#air_quality(city = '') ⇒ Object



26
27
28
29
30
31
32
33
34
35
# File 'lib/ale_air/fetch_json.rb', line 26

def air_quality(city = '')
  return error('Missing API token') if @secret_token.empty?

  document = get_json("/search/?keyword=#{cleaned(city)}&token=#{@secret_token}")
  get_info(document)
rescue NetworkError => e
  error("Network error: #{e.message}")
rescue JSON::ParserError => e
  error("Invalid JSON response: #{e.message}")
end