Advertisement
Azure

weather script test

May 29th, 2012
351
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Ruby 5.44 KB | None | 0 0
  1. # coding: utf-8
  2. require 'geocoder'
  3. require 'json'
  4. require 'open-uri'
  5.  
  6. set_items = :minimal
  7. set_units = :both
  8. apikey = "NOTTELLINGYOU"
  9.  
  10. # Take the supplied query and geocode it
  11. results = Geocoder.search("Amherst, NS").first
  12. # Get the current conditions for the geocoded query using latlong.
  13. conditions = JSON.parse open("http://api.wunderground.com/api/#{apikey}/conditions/almanac/astronomy/q/#{results.latitude},#{results.longitude}.json").read
  14. observations = conditions["current_observation"]
  15. almanac = conditions["almanac"]
  16. moon = conditions["moon_phase"]
  17.  
  18. Temperature = Struct.new(:celsius, :fahrenheit, :unit) do
  19.   def to_s *args
  20.     return "" if self.celsius.eql?("NA") || self.celsius.to_s.empty? || self.celsius.nil?
  21.     case self.unit
  22.     when :both then "#{self.celsius}°C (#{self.fahrenheit}°F)"
  23.     when :metric then "#{self.celsius}°C"
  24.     when :imperial then "#{self.fahrenheit}°F"
  25.     else
  26.       "#{self.celsius}°C (#{self.fahrenheit}°F)"
  27.     end
  28.   end
  29. end
  30.  
  31. Distance = Struct.new(:km, :mi, :perhour, :unit) do
  32.   def to_s *args
  33.     return "" if self.km.eql?("NA") || self.km.eql?("N/A") || self.km.nil?
  34.     u = {
  35.       km: (self.perhour ? "km/h" : "km"),
  36.       mi: (self.perhour ? "mph" : "mi")
  37.     }
  38.     case self.unit
  39.     when :both then "#{self.km} #{u[:km]} (#{self.mi} #{u[:mi]})"
  40.     when :metric then "#{self.km} #{u[:km]}"
  41.     when :imperial then "#{self.mi} #{u[:mi]}"
  42.     else
  43.       "#{self.km} #{u[:km]} (#{self.mi} #{u[:mi]})"
  44.     end
  45.   end
  46. end
  47.  
  48. Fluid = Struct.new(:mm, :in, :unit) do
  49.   def to_s *args
  50.     return "" if self.mm.to_i == 0 || self.mm.nil?
  51.     case self.unit
  52.     when :both then "#{self.mm} mm (#{self.in} in)"
  53.     when :metric then "#{self.mm} mm"
  54.     when :imperial then "#{self.in} in"
  55.     else
  56.       "#{self.mm} mm (#{self.in} in)"
  57.     end
  58.   end
  59. end
  60.  
  61. pressure_trend = ->(pt) {
  62.   case pt.to_s
  63.   when "+" then "rising"
  64.   when "0" then "steady"
  65.   when "-" then "falling"
  66.   else
  67.     nil
  68.   end
  69. }
  70.  
  71. precip = ->(onehour_mm, today_mm, onehour_in, today_in) {
  72.   return "" if onehour_mm.to_i < 1 && today_mm.to_i < 1
  73.   parts = []
  74.   parts << "#{Fluid.new(onehour_mm.to_i, onehour_in.to_i, set_units).to_s} in the past hour" unless onehour_mm.to_i < 1
  75.   parts << "#{Fluid.new(today_mm.to_i, today_in.to_i, set_units).to_s} today" unless today_mm.to_i < 1
  76.   parts.join(", and ")
  77. }
  78.  
  79. wind = ->(dir, kph, gust_kph, mph, gust_mph) {
  80.   return nil if [kph, gust_kph, mph, gust_mph].all? {|i| i.to_f <= 0.00 }
  81.   parts = []
  82.   parts << "#{dir} at #{Distance.new(kph, mph, true, set_units).to_s}"
  83.   parts << "gusting to #{Distance.new(gust_kph, gust_mph, true, set_units).to_s}" if gust_mph.to_f > 0
  84.   parts.join(", ")
  85. }
  86.  
  87. uv = ->(index) {
  88.   case index.to_f
  89.   when 0..2 then "Low" #Format(:green,"Low")
  90.   when 3..5 then "Moderate" #Format(:yellow,"Moderate")
  91.   when 6..7 then "High" #Format(:orange,"High")
  92.   when 8..10 then "Very High" #Format(:red,"Very High")
  93.   when 11..Float::INFINITY then "Extreme" #Format(:violet,"Extreme")
  94.   else
  95.     index.to_s
  96.   end
  97. }
  98.  
  99. outside = []
  100. outside << observations["weather"] unless observations["weather"].empty?
  101. outside << "#{Temperature.new(observations["temp_c"], observations["temp_f"], set_units).to_s}, feels like #{Temperature.new(observations["feelslike_c"], observations["feelslike_f"], set_units).to_s}"
  102.  
  103. data = {
  104.   "High/Low" => Temperature.new(almanac["temp_high"]["normal"]["C"], almanac["temp_high"]["normal"]["F"], set_units).to_s + "/" + Temperature.new(almanac["temp_low"]["normal"]["C"], almanac["temp_low"]["normal"]["F"], set_units).to_s,
  105.   "Dew point" => Temperature.new(observations["dewpoint_c"], observations["dewpoint_f"], set_units),
  106.   "Humidity" => (observations["relative_humidity"].to_i < 0 ? "N/A" : observations["relative_humidity"]),
  107.   "Precip" => precip.call(observations["precip_1hr_metric"], observations["precip_today_metric"], observations["precip_1hr_in"], observations["precip_today_in"]),
  108.   "Wind" => wind.call(observations["wind_dir"], observations["wind_kph"], observations["wind_gust_kph"], observations["wind_mph"], observations["wind_gust_mph"]),
  109.   "Wind chill" => Temperature.new(observations["windchill_c"], observations["windchill_f"], set_units),
  110.   "Heat index" => Temperature.new(observations["heat_index_c"], observations["heat_index_f"], set_units),
  111.   "Pressure" => "#{(observations["pressure_mb"].to_i / 10.00).round(2)} kPa #{pressure_trend.call(observations["pressure_trend"])}",
  112.   "Visibility" => Distance.new(observations["visibility_km"], observations["visibility_mi"], false, set_units),
  113.   "UV Index" => ((uv.call(observations["UV"]) + " (#{observations["UV"]})") unless observations["UV"].to_i < 0),
  114.   "Sunrise/set" => "#{DateTime.parse(moon["sunrise"].values.join(":")).strftime("%-l:%M%P")}, #{DateTime.parse(moon["sunset"].values.join(":")).strftime("%-l:%M%P")}"
  115. }
  116. minimal_data = ["Wind","Visibility","UV Index","Sunrise/set"]
  117.  
  118. data.reject! {|k,v| v.to_s.empty? || (set_items == :minimal && !minimal_data.include?(k)) }
  119. collected = data.collect {|k,v|
  120.   "#{k}: #{v}"
  121. }.join("; ")
  122.  
  123. head = "Current observations for %<location>s (#{observations["station_id"]}) at %<observation_time>s:" % {
  124.   location: observations["display_location"]["full"],
  125.   observation_time: DateTime.parse(observations["local_time_rfc822"]).strftime("%b %-d, %Y, %-l:%M%P")
  126. }
  127. foot = "The full forecast can be viewed at #{observations["forecast_url"] + "?apiref=3fc95544aab994a0"}"
  128.  
  129. puts [head,[*outside,collected].join(", "),foot].join("\n")
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement