-
Notifications
You must be signed in to change notification settings - Fork 0
/
forecast.rb
248 lines (219 loc) · 7.35 KB
/
forecast.rb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
require 'yaml'
require 'rubygems'
require 'hashie'
begin
require 'colorize'
rescue LoadError
class String
def yellow() self; end
def red() self; end
end
end
require 'i18n' # internationalization
# find default locales here:
# https://github.com/svenfuchs/rails-i18n/tree/master/rails/locale
class Forecast
DARKSKY_OFFLINE = 'darksky-unavailable'
def self.data_dir
@@data_dir
end
def self.setup
@@data_dir = File.join(
File.dirname(File.expand_path(__FILE__)), 'config')
@@units = YAML.load(File.read(File.join(@@data_dir, 'units.yml')))
@@units_regexp = Regexp.new(@@units['us'].keys.join('|'), Regexp::IGNORECASE)
@@icons = YAML.load(File.read(File.join(@@data_dir, 'icons.yml')))
@@icons.default = @@icons.delete 'default'
@@moon = @@icons.delete 'moon'
@@compass = %w(N NNE NE ENE E ESE SE SSE S SSW SW WSW W WNW NW NNW)
I18n.load_path += Dir[File.join(
@@data_dir, 'locales', '*.{rb,yml}')]
I18n.locale = I18n.default_locale
validate_rubyversion
end
def self.validate_rubyversion
# prior to ruby 2.3.0, sprintf does not support hash default values
# and fails if there is no explicit value set. we need to explicitly
# set all attributes to NA.
@@set_flat_data_defaults = Gem::Version.new(RUBY_VERSION) < Gem::Version.new('2.3.0')
end
private_class_method :validate_rubyversion
attr_reader :options
def options=(opts)
@options = opts
I18n.locale = options.language if options.language?
@flat_data[:location] = options.location
@flat_data[:latitude] = options.latitude
@flat_data[:longitude] = options.longitude
@flat_data[:coordinates] =
I18n.t('coordinates') % [options.latitude, options.longitude]
@flat_data[:position] = @flat_data[:location] || @flat_data[:coordinates]
end
attr_reader :data
attr_reader :units
def initialize(forecast)
@data = forecast
@units = @@units[forecast.flags.units]
@flat_data = Hash.new
@options = Hashie::Mash.new()
end
def print(format)
make_flat_data(data)
puts format.gsub("\n",'').gsub("\\\\","\n") % @flat_data
end
def deg_to_compass(degree)
@@compass[(degree/22.5).round % 16]
end
def moon(phase)
@@moon[(phase/0.125).round % 8]
end
def bearing(degree, size)
I18n.t "bearing.#{deg_to_compass(degree)}.#{size}"
end
def unit(type)
I18n.t "units.#{units[type]}"
end
def wind(obj)
I18n.t('wind') %
[obj.windSpeed, unit(:speed), bearing(obj.windBearing, 'long')]
end
def alert_messages
message = ''
append_network_notifications(message)
append_alerts(message)
append_nearest_storm_message(message)
return message
end
private
def make_flat_data(forecast)
@flat_data.default = I18n.t('default_value')
set_flat_data_defaults if @@set_flat_data_defaults
recursive_flat_data([], forecast)
end
def recursive_flat_data(keys, object)
keys.pop if keys.last == 'data'
if object.kind_of? Hash
object.each_pair { |k,v| recursive_flat_data(keys + [k], v) }
elsif object.kind_of? Array
object.each_with_index { |v,i| recursive_flat_data(keys + [i.to_s], v) }
else
name = keys.last
key = to_key(keys)
@flat_data[key] = case name
when /error\Z/i then percentage(object)
when /time\Z/i, 'expires' then time(@flat_data, object, keys)
when /bearing\Z/i
@flat_data[to_key(keys + ['short'])] = bearing(object, 'short')
@flat_data[to_key(keys + ['long'])] = bearing(object, 'long')
bearing(object, 'long')
when @@units_regexp then unit_message(object, $&, keys)
when 'icon'
@flat_data[to_key(keys + ['text'])] = object
@@icons[object]
when 'moonPhase' then moon(object)
when 'precipProbability'
precipType = to_key(keys[0...-1] << 'precipType')
if not @flat_data.has_key? precipType
@flat_data[precipType] = I18n.t('precipitation.default')
end
percentage(object)
when 'dewPoint' then unit_message(object, :temperature, keys)
when 'cloudCover' then percentage(object)
when 'humidity' then percentage(object)
when 'visibility' then unit_message(object, :distance, keys)
else object
end
end
end
def set_flat_data_defaults
# ruby versions prior to 2.3.0 do not support hash default arguments in sprintf.
# this means that this app will crash if the output format specification
# asks for attributes which are not present in the received data.
# we initialise the hash with all values listed in the api-specification.
layout = Hashie::Mash.new(YAML.load(File.read(File.join(@@data_dir, 'api.yml'))))
set_flat_data_default([], layout['structure'], layout)
end
def set_flat_data_default(keys, object, layout)
if object.kind_of? Hash
object.each_pair do |key, value|
set_flat_data_default(keys + [key], value, layout)
end
elsif object.kind_of? Array
size, elem = object
0.upto(size).each do |i|
set_flat_data_default(keys + [i.to_s], elem, layout)
end
set_flat_data_default(keys, 'datablock', layout)
else
layout[object].each do |entry|
@flat_data[to_key(keys + [entry])] = I18n.t('default_value')
end
end
end
def to_key(key_parts)
key_parts.join('.').to_sym
end
def time(store, time, keys)
time = Time.at(time)
time_formats = I18n.backend.__send__(:translations)[:en][:time][:formats]
default = 'NA'
time_formats.each do |name, _|
default = I18n.l(time, {format: name}) if name == :default
store[to_key(keys+[name])] = I18n.l(time, {format: name})
end
return default
end
def unit_message(value, type, keys=nil)
type[0] = type[0].downcase if type.kind_of? String
if !keys.nil?
@flat_data[to_key(keys + ['short'])] =
I18n.t('unit_message') % [value.round.to_s, unit(type.to_sym)]
end
I18n.t('unit_message') % [value.to_s, unit(type.to_sym)]
end
def percentage(value)
I18n.t('percent') % (100*value)
end
def append_network_notifications(message)
if data.flags.has_key? DARKSKY_OFFLINE
info = data.flags[DARKSKY_OFFLINE].inspect
message << I18n.t('darksky.offline').yellow % info
end
end
def append_alerts(message)
data.alerts!.each do |alert|
message << alert_message(alert).red
end
end
def alert_message(alert)
message = alert_title(alert)
message << "\n"
message << alert.description << "\n" if alert.description?
message << alert.uri << "\n" if alert.uri?
end
def alert_title(alert)
if alert.expires?
alert_time = I18n.l(Time.at(alert.expires))
if alert.title?
title = I18n.t('alert.titled.with_time') % [alert.title, alert_time]
else
title = I18n.t('alert.simple.with_time') % alert_time
end
elsif alert.title?
title = I18n.t('alert.titled.base') % alert.title
else
title = I18n.t('alert.simple.base')
end
return title.bold
end
def append_nearest_storm_message(message)
if data.currently.nearestStormDistance! < options.storm_warn_distance
message << I18n.t('storm.near').yellow % [
forecast.currently.nearestStormDistance, unit(:distance),
(options.location || @flat_data[:coordinates]),
deg_to_compass(forecast.currently.nearestStormBearing)
]
end
end
end
Forecast.setup