generated from appdev-projects/ruby-template
-
Notifications
You must be signed in to change notification settings - Fork 371
/
do_not_peek_possible_solution.rb
101 lines (62 loc) · 2.47 KB
/
do_not_peek_possible_solution.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
require "http"
require "json"
require "dotenv/load"
line_width = 40
puts "=" * line_width
puts "Will you need an umbrella today?".center(line_width)
puts "=" * line_width
puts
puts "Where are you?"
user_location = gets.chomp
# user_location = "Saint Paul"
puts "Checking the weather at #{user_location}...."
# Get the lat/lng of location from Google Maps API
gmaps_key = ENV.fetch("GMAPS_KEY")
gmaps_url = "https://maps.googleapis.com/maps/api/geocode/json?address=#{user_location}&key=#{gmaps_key}"
# p "Getting coordinates from:"
# p gmaps_url
raw_gmaps_data = HTTP.get(gmaps_url)
parsed_gmaps_data = JSON.parse(raw_gmaps_data)
results_array = parsed_gmaps_data.fetch("results")
first_result_hash = results_array.at(0)
geometry_hash = first_result_hash.fetch("geometry")
location_hash = geometry_hash.fetch("location")
latitude = location_hash.fetch("lat")
longitude = location_hash.fetch("lng")
puts "Your coordinates are #{latitude}, #{longitude}."
# Get the weather from Pirate Weather API
pirate_weather_key = ENV.fetch("PIRATE_WEATHER_KEY")
pirate_weather_url = "https://api.pirateweather.net/forecast/#{pirate_weather_key}/#{latitude},#{longitude}"
# p "Getting weather from:"
# p pirate_weather_url
raw_pirate_weather_data = HTTP.get(pirate_weather_url)
parsed_pirate_weather_data = JSON.parse(raw_pirate_weather_data)
currently_hash = parsed_pirate_weather_data.fetch("currently")
current_temp = currently_hash.fetch("temperature")
puts "It is currently #{current_temp}°F."
# Some locations around the world do not come with minutely data.
minutely_hash = parsed_pirate_weather_data.fetch("minutely", false)
if minutely_hash
next_hour_summary = minutely_hash.fetch("summary")
puts "Next hour: #{next_hour_summary}"
end
hourly_hash = parsed_pirate_weather_data.fetch("hourly")
hourly_data_array = hourly_hash.fetch("data")
next_twelve_hours = hourly_data_array[1..12]
precip_prob_threshold = 0.10
any_precipitation = false
next_twelve_hours.each do |hour_hash|
precip_prob = hour_hash.fetch("precipProbability")
if precip_prob > precip_prob_threshold
any_precipitation = true
precip_time = Time.at(hour_hash.fetch("time"))
seconds_from_now = precip_time - Time.now
hours_from_now = seconds_from_now / 60 / 60
puts "In #{hours_from_now.round} hours, there is a #{(precip_prob * 100).round}% chance of precipitation."
end
end
if any_precipitation == true
puts "You might want to take an umbrella!"
else
puts "You probably won't need an umbrella."
end