ruby
41 lines · 7 steps
Coercing request params by schema in Ruby
A small class turns raw string params into typed values using a lambda-per-type lookup table and per-key options.
Explained by
highlit
1class ParamCoercer
2 TYPES = {
3 integer: ->(v) { Integer(v) },
4 float: ->(v) { Float(v) },
5 boolean: ->(v) { %w[1 true yes on].include?(v.to_s.downcase) },
6 string: ->(v) { v.to_s.strip },
7 date: ->(v) { Date.iso8601(v) },
8 array: ->(v) { Array(v).map(&:to_s) }
9 }.freeze
10
11 def initialize(schema)
12 @schema = schema
13 end
14
15 def coerce(params)
16 @schema.each_with_object({}) do |(key, options), result|
17 options = { type: options } unless options.is_a?(Hash)
18 raw = params[key.to_s]
19
20 if raw.nil? || raw == ""
21 result[key] = options[:default] if options.key?(:default)
22 next
23 end
24
25 coercer = TYPES.fetch(options[:type]) do
26 raise ArgumentError, "unknown type #{options[:type].inspect} for #{key}"
27 end
28
29 value = coercer.call(raw)
30
31 if (allowed = options[:in]) && !allowed.include?(value)
32 result[key] = options[:default] if options.key?(:default)
33 next
34 end
35
36 result[key] = value
37 rescue ArgumentError, TypeError, Date::Error
38 result[key] = options[:default] if options.key?(:default)
39 end
40 end
41end
01 / 01
STEP 01
‹ swipe to step through ›
Walkthrough
Space play
←→ step
click any line
Three takeaways
- 1A frozen hash of lambdas is a clean way to dispatch behavior by a symbol key instead of a case statement.
- 2Normalizing shorthand options into a full hash lets callers use either a bare type or a rich config.
- 3Wrapping coercion in a rescue turns conversion failures into graceful defaults rather than crashes.
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/coercing-request-params-by-schema-in-ruby-explained-ruby-b8ae/embed?autoplay=1" width="100%" height="520" loading="lazy" style="border:0"></iframe>
Autoplay is on by default — add ?autoplay=0 to start paused.