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
‹ swipe to step through ›
Walkthrough
Space play
←→ step
click any line
Three takeaways
- 1Wrapping low-level network exceptions in domain-specific errors gives callers a stable contract to rescue against.
- 2Setting explicit open and read timeouts prevents a slow upstream from hanging your request indefinitely.
- 3A memoized URI builder keeps query construction declarative and separate from the request logic.
Related explainers
rust
use serde::Deserialize; #[derive(Debug, Deserialize)] #[serde(untagged)]
Parsing flexible JSON shapes with serde
deserialization
enums
json
Intermediate
6 steps
ruby
require "shellwords" require "open3" module Backup
Building safe shell commands in Ruby
shell-out
subprocess
command-injection
Intermediate
7 steps
ruby
class UserAgentParser BROWSERS = [ [/Edg\/([\d.]+)/, "Edge"], [/OPR\/([\d.]+)/, "Opera"],
Parsing user-agent strings in Ruby
regex
pattern-matching
lookup-tables
Intermediate
8 steps
ruby
class LogAggregator BUCKET_FORMAT = "%Y-%m-%dT%H:%M" def initialize(entries)
Bucketing log entries by the minute in Ruby
aggregation
hashing
enumerable
Intermediate
5 steps
ruby
class WeeklySignupsReport DEFAULT_WEEKS = 12 def initialize(weeks: DEFAULT_WEEKS, source: User.all)
Building a weekly signups report in Rails
service object
aggregation
group by
Intermediate
7 steps
rust
use chrono::{Duration, NaiveDate}; #[derive(Debug)] pub struct DateRange {
Parsing and iterating date ranges in Rust
error-handling
iterators
parsing
Intermediate
7 steps
Share this explainer
Here's the card — post it anywhere.
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code
Embed this explainer
Drop the interactive walkthrough into a blog or docs. Views never cost a credit.
<iframe src="https://highlit.co/explainers/a-resilient-weather-api-service-object-in-rails-explained-ruby-6b76/embed?autoplay=1" width="100%" height="520" loading="lazy" style="border:0"></iframe>
Autoplay is on by default — add ?autoplay=0 to start paused.