Class: Barabara::Modules::Wttr

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

Instance Method Summary collapse

Constructor Details

#initializeWttr

Returns a new instance of Wttr.



10
11
12
13
14
15
16
17
# File 'lib/barabara/modules/wttr.rb', line 10

def initialize
  options = GlobalConfig.config.module_config('weather')
  @colors = GlobalConfig.config.colors
  @location = options['location'] || 'London'
  @unit = (options['unit'] || 'c') == 'c' ? 'm' : 'u'
  @format = options['format']
  @uri = format_uri
end

Instance Method Details

#fetchObject



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

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

#format_uriObject



19
20
21
22
23
24
# File 'lib/barabara/modules/wttr.rb', line 19

def format_uri
  uri = URI("https://wttr.in/#{@location}")
  query = URI.encode_www_form(@unit => nil, 'format' => "%c\t%t")
  uri.query = query
  uri
end

#parse!Object



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

def parse!
  @icon, rawtemp = @raw_data.body.split("\t")
  @temp = rawtemp.to_i
end

#renderObject



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

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

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

#watchObject



49
50
51
52
53
54
# File 'lib/barabara/modules/wttr.rb', line 49

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