Я создаю простое приложение Rails, которое использует API Open Weather Map и возвращает различные параметры погоды. Мой вызов API обрабатывается в классе обслуживания, и я пытаюсь следовать шаблону фасада и работать с данными параметров в PORO. Код у меня уже есть ниже. Я получаю NameError. undefined local variable or method
city'` Есть идеи, где я иду не так?
приложение / услуги / 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
приложение / фасадов / forecasts_facade.rb
class ForecastsFacade
TOKEN = Rails.application.credentials.openweather_key
def initialize(city, forecast, temperature, weather_code, description, wind, humidity)
@city = city
@forecast = forecast
@temperature = temperature
@weather_code = weather_code
@description = description
@wind = wind
@humidity = humidity
end
def city
@city = params[:q]
end
def forecast
if @city.nil?
@forecast = {}
else
@forecast = OpenWeatherApi.new(@city, TOKEN).my_location_forecast
end
end
def temperature
@temperature = @forecast.dig('main', 'temp').to_i - 273
end
def weather_code
@weather_code = @forecast.dig('weather', 0, 'id').to_i
end
def description
@description = @forecast.dig('weather', 0, 'description')
end
def wind
@wind = @forecast.dig('wind', 'speed').to_i
end
def humidity
@humidity = @forecast.dig('main', 'humidity')
end
end
forecasts_controller.rb
class ForecastsController < ApplicationController
def current_weather
@forecasts_facade = ForecastsFacade.new(city, forecast, temperature, weather_code, description, wind, humidity)
end
end
current_weather.html.erb
<div class="page-wrapper">
<h1 class="title">The weather in GIFs</h1>
<div class="search">
<%= form_tag(current_weather_forecasts_path, method: :get) do %>
<%= text_field_tag :q, nil, placeholder: "Enter a city", class: "search-field" %>
<%= button_tag type: 'submit', class: "search-button" do %>
<i class="fas fa-search"></i>
<% end %>
<% end %>
</div>
<% if ForecastsFacade.forecast.dig('cod').to_i == 404 %>
<p>Please use a valid city name!</p>
<% elsif ForecastsFacade.forecast.dig('cod').to_i == 400 %>
<p>Please type in a city name!</p>
<% elsif ForecastsFacade.forecast == {} %>
<% else %>
<p class="weather-description"><%= "#{ForecastsFacade.city.capitalize}: #{ForecastsFacade.description}" %></p>
<div class="gif-container"><%= image_tag(find_gif_url, class: "gif") %>
<span class="temperature weather-attribute"><%= "#{ForecastsFacade.temperature}°C" %></span>
<span class="wind weather-attribute"><%= "wind:#{(ForecastsFacade.wind * 3.6).to_i}km/h" %></span> <!-- converts to km/hr -->
<span class="humidity weather-attribute"><%= "humidity:#{ForecastsFacade.humidity}%" %></span>
</div>
<% end %>
</div>