Created
February 1, 2017 15:45
-
-
Save boykoc/63bb23a1640a0d25daae05a1acb7a70e to your computer and use it in GitHub Desktop.
Ruby script to print the weather. This is setup to run from cmd line for Ontario, Canada as the default area using Environment Canada.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
module WeatherChecker | |
require 'rubygems' | |
require 'nokogiri' | |
require 'open-uri' | |
# Setup proxy just for this. | |
# Modify this to work for your needs/setup. Remove if you aren't behind a proxy. | |
system 'export http_proxy=$https_proxy' | |
city_directory_url = 'https://weather.gc.ca/forecast/canada/index_e.html?id=ON' | |
default_city = 'Toronto' | |
## | |
# Print the city and it's 7 day forcast. | |
def self.print_weather(p) | |
puts p.css('title').text | |
temps = p.css('.pdg-btm-0') | |
temps.each do |temp| | |
puts "\e[1m" + temp.css('strong').text.strip + "\e[0;32m" | |
puts temp.css('td:last-child').text.strip | |
end | |
end | |
# Check if parameter passed. | |
if ARGV[0] | |
begin | |
# Make a request to the URL. | |
page = Nokogiri::HTML(open(city_directory_url)) | |
# Find the city URL. | |
city_link = 'https://weather.gc.ca' + page.css('a').select { |link| link.text.downcase == ARGV[0].downcase }.first['href'] | |
# Go to the City page. | |
page = Nokogiri::HTML(open(city_link)) | |
print_weather(page) | |
rescue | |
puts 'Uh-Oh! Something went wrong. Maybe you should try again.' | |
end | |
else | |
begin | |
# Use default. | |
puts "You didn't specify the city, so here is #{default_city} weather" | |
# Make a request to the URL. | |
page = Nokogiri::HTML(open(city_directory_url)) | |
# Find the city URL. | |
city_link = 'https://weather.gc.ca' + page.css('a').select { |link| link.text.downcase == default_city.downcase }.first['href'] | |
# Go to the City page. | |
page = Nokogiri::HTML(open(city_link)) | |
print_weather(page) | |
rescue | |
puts 'Uh-Oh! Something went wrong. Maybe you should try again.' | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment