I have a simple app that calls an API and returns weather data. A user is able to search for a city and the current temperature is returned. I have a problem though, when the search field is empty or a city that isn't recognised I get an error undefined method
[]' for nil:NilClass`. Here is my code:
forecasts_controller.rb
class ForecastsController < ApplicationController
def current_weather
@token = Rails.application.credentials.openweather_key
@city = params[:q]
if @city == nil
@forecast = ""
else
@forecast = OpenWeatherApi.new(@city, @token).my_location_forecast
end
end
end
services/open_weather_api.rb
class OpenWeatherApi
include HTTParty
base_uri "http://api.openweathermap.org"
def initialize(city, appid)
@options = { query: { q: city, APPID: appid } }
end
def my_location_forecast
self.class.get("/data/2.5/weather", @options)
end
end
current_weather.html.erb
<%= form_tag(current_weather_forecasts_path, method: :get) do %>
<%= text_field_tag(:q) %>
<%= submit_tag("Search") %>
<% end %><br>
<p>Current temperature: <%= @forecast['main']['temp'].to_i - 273 %>°C</p>
Obviously the code ['main']['temp'].to_i - 273
can't be called on nil
, but how do I prevent @forecast
from being nil
when nothing is passed in the form or when the API doesn't recognise the city?