ruby 49 lines · 7 steps

A resilient weather API service object in Rails

A plain Ruby service object that fetches weather over HTTPS and translates network failures into meaningful domain errors.

Explained by highlit
1class WeatherLookup
2 Result = Struct.new(:temperature, :conditions, keyword_init: true)
3 
4 class TimeoutError < StandardError; end
5 class UpstreamError < StandardError; end
6 
7 OPEN_TIMEOUT = 2
8 READ_TIMEOUT = 5
9 
10 def initialize(latitude:, longitude:)
11 @latitude = latitude
12 @longitude = longitude
13 end
14 
15 def call
16 response = perform_request
17 
18 unless response.is_a?(Net::HTTPSuccess)
19 raise UpstreamError, "weather API responded #{response.code}"
20 end
21 
22 payload = JSON.parse(response.body).fetch("current")
23 Result.new(temperature: payload["temperature_2m"], conditions: payload["weather_code"])
24 rescue Net::OpenTimeout, Net::ReadTimeout => e
25 raise TimeoutError, "weather API timed out: #{e.message}"
26 end
27 
28 private
29 
30 def perform_request
31 http = Net::HTTP.new(uri.host, uri.port)
32 http.use_ssl = true
33 http.open_timeout = OPEN_TIMEOUT
34 http.read_timeout = READ_TIMEOUT
35 http.get(uri.request_uri, "Accept" => "application/json")
36 end
37 
38 def uri
39 @uri ||= URI::HTTPS.build(
40 host: "api.open-meteo.com",
41 path: "/v1/forecast",
42 query: {
43 latitude: @latitude,
44 longitude: @longitude,
45 current: "temperature_2m,weather_code"
46 }.to_query
47 )
48 end
49end
01 / 01
STEP 01

Walkthrough

Space play step click any line
Three takeaways
  1. 1Wrapping low-level network exceptions in domain-specific errors gives callers a stable contract to rescue against.
  2. 2Setting explicit open and read timeouts prevents a slow upstream from hanging your request indefinitely.
  3. 3A memoized URI builder keeps query construction declarative and separate from the request logic.

Related explainers

Share this explainer

Here's the card — post it anywhere.

A resilient weather API service object in Rails — share card
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code