class Services::Infrastructure::Adapters::Weather::GoogleWeatherBase
Base class for Google Weather API adapters
Subclasses must implement (private methods):
-
base_url — API endpoint URL
-
cache_prefix — prefix for cache keys
-
response_class — class to wrap the JSON response
-
response_key — key in the JSON that indicates success (e.g.
"currentTime","forecastHours") -
error_label — string used in error messages (e.g.
"current weather")
Optionally override extra_params for additional query parameters (e.g. days: 7, hours: 12).
Responses are cached for 30 minutes per location.
Public Class Methods
Source
# File app/services/infrastructure/adapters/weather/google_weather_base.rb 21 def initialize 22 @api_key = Rails.configuration.weather_app.google_places_api_key 23 @cache = Rails.cache 24 end
Public Instance Methods
Source
# File app/services/infrastructure/adapters/weather/google_weather_base.rb 42 def call(latitude, longitude, zipcode: nil) 43 cache_key = build_cache_key(latitude, longitude, zipcode) 44 45 cached_response = @cache.read(cache_key) 46 return response_class.new(cached_response, :cached_response) if cached_response.present? 47 48 uri = URI.parse(base_url) 49 uri.query = URI.encode_www_form( 50 { key: @api_key, "location.latitude": latitude, "location.longitude": longitude }.merge(extra_params) 51 ) 52 53 response = Net::HTTP.get_response(uri) 54 raise Error, "Failed to fetch #{error_label} data" unless response.is_a?(Net::HTTPSuccess) 55 56 response_data = JSON.parse(response.body) 57 raise NotFoundError, "No #{error_label} data found for coordinates: #{latitude}, #{longitude}" unless response_data[response_key].present? 58 59 @cache.write(cache_key, response_data, expires_in: 30.minutes) 60 response_class.new(response_data, :api_response) 61 end
Fetches weather data for the given coordinates.
Parameters
-
latitude (
Float) — Latitude. -
longitude (
Float) — Longitude. -
zipcode (
String, optional) — When present, used in the cache key so nearby coordinates share the same cache entry.
Returns
An instance of the subclass’s response_class (e.g. GoogleCurrentWeatherResponse).
Raises
-
NotFoundErrorwhen the API returns no data for the coordinates. -
Errorwhen the HTTP request fails.