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

Walkthrough

Space play step click any line
Three takeaways
  1. 1A frozen hash of lambdas is a clean way to dispatch behavior by a symbol key instead of a case statement.
  2. 2Normalizing shorthand options into a full hash lets callers use either a bare type or a rich config.
  3. 3Wrapping coercion in a rescue turns conversion failures into graceful defaults rather than crashes.

Related explainers

Share this explainer

Here's the card — post it anywhere.

Coercing request params by schema in Ruby — share card
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code