class Barabara::Modules::Weather

Public Class Methods

new() click to toggle source
# 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

Public Instance Methods

cond_icon(condition) click to toggle source
# 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
fetch() click to toggle source
# File lib/barabara/modules/weather.rb, line 32
def fetch
  Net::HTTP.get_response(@uri)
rescue SocketError
  '⌚'
end
format_uri(api_key, location) click to toggle source
# 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!() click to toggle source
# 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
render() click to toggle source
# 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
watch() click to toggle source
# File lib/barabara/modules/weather.rb, line 64
def watch
  loop do
    publish(:event, 'weather', render)
    sleep 900
  end
end