Method: Weatherbot::API.current_weather

Defined in:
lib/api.rb

.current_weather(location) ⇒ Object

Takes user input to enter into URL query & gets current weather conditions in imperial units



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
# File 'lib/api.rb', line 17

def self.current_weather(location)
  # query sample: 'https://api.openweathermap.org/data/2.5/weather?q=new+york&appid=3207703ee5d0d14e6b6a53d10071018f&units=imperial'
  response = HTTParty.get("https://api.openweathermap.org/data/2.5/weather?q=#{location}&appid=3207703ee5d0d14e6b6a53d10071018f&units=imperial")
  parsed = response.parsed_response
  @current = self.new
  @current.response_code = parsed["cod"]

  # Check for invalid entry
  if @current.response_code === "404"
    puts "\n\nInvalid location, please enter a valid location.\n\n"
    return
  else
    # Assign attributes to current weather object
  @current.coordinates = parsed["coord"].values.reverse.join(", ")
  @current.location_name = parsed["name"]
  @current.report_time = Time.at(parsed["dt"])
  @current.temp_avg = parsed["main"]["temp"]
  @current.condition = parsed["weather"].first["description"]
  @current.cloudiness = parsed["clouds"]["all"]
  # @current.pressure = parsed["main"]["pressure"]
  @current.humidity = parsed["main"]["humidity"]
  @current.wind_speed = parsed["wind"]["speed"]
  @current.sunrise = Time.at(parsed["sys"]["sunrise"])
  @current.sunset = Time.at(parsed["sys"]["sunset"])
  @current.wind_direction = degToCompass(parsed["wind"]["deg"])
  @current.temp_celsius = toCelsius(parsed["main"]["temp"])

  # Open query in browser to Google Maps
  @current.google_maps = "https://www.google.com/maps/place/#{@current.coordinates.gsub(" ", "")}"
  @google_maps_link = @current.google_maps

  # Check for odd locations with no country key
  if parsed.fetch("sys").has_key?("country")
    @current.country = parsed["sys"]["country"]
  else
    @current.country = nil
  end


  end

  @current
end