Class: Barabara::Modules::Weather

Inherits:
Object
  • Object
show all
Includes:
Wisper::Publisher
Defined in:
lib/barabara/modules/weather.rb

Instance Method Summary collapse

Constructor Details

#initializeWeather

Returns a new instance of Weather.



11
12
13
14
15
16
17
18
19
20
21
22
23
# File 'lib/barabara/modules/weather.rb', line 11

def initialize
  options = GlobalConfig.config.module_config('weather')
  @colors = GlobalConfig.config.colors

  @api_key = options['api_key'] || '0'
  @location = options['location'] || 'London'
  @uri = format_uri(@api_key, @location)
  @raw_data = fetch
  @temp = 0
  @unit = options['unit'] || 'c'
  @icon = '?'
  @format = options['format']
end

Instance Method Details

#cond_icon(condition) ⇒ Object



38
39
40
41
42
43
44
45
46
# File 'lib/barabara/modules/weather.rb', line 38

def cond_icon(condition)
  case condition
  when /cloudy|cast|fog|mist/i then ''
  when /clear|sunny/i then ''
  when /outbreaks|rain|drizzle|thunder/i then ''
  when /sleet|ice|snow/i then ''
  else '?'
  end
end

#fetchObject



32
33
34
35
36
# File 'lib/barabara/modules/weather.rb', line 32

def fetch
  Net::HTTP.get_response(@uri)
rescue SocketError
  ''
end

#format_uri(api_key, location) ⇒ Object



25
26
27
28
29
30
# File 'lib/barabara/modules/weather.rb', line 25

def format_uri(api_key, location)
  uri = URI('http://api.apixu.com/v1/current.json')
  query = URI.encode_www_form(key: api_key, q: location)
  uri.query = query
  uri
end

#parse!Object



48
49
50
51
52
# File 'lib/barabara/modules/weather.rb', line 48

def parse!
  weatherdata = JSON.parse(@raw_data.body)['current']
  @temp, condition = weatherdata.fetch_values("temp_#{@unit}", 'condition')
  @icon = cond_icon(condition['text'])
end

#renderObject



54
55
56
57
58
59
60
61
62
# File 'lib/barabara/modules/weather.rb', line 54

def render
  @raw_data = fetch
  return '' unless @raw_data.is_a?(Net::HTTPSuccess)

  parse!
  sign = '+' if @temp.positive?
  format(@format,
         { temp: "#{sign}#{@temp.to_i}", icon: @icon }.merge(@colors))
end

#watchObject



64
65
66
67
68
69
# File 'lib/barabara/modules/weather.rb', line 64

def watch
  loop do
    publish(:event, 'weather', render)
    sleep 900
  end
end