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
python
import time from concurrent.futures import ThreadPoolExecutor, as_completed from pathlib import Path
Parallel file downloads with a thread pool
concurrency
thread-pool
streaming-io
Intermediate
8 steps
go
package validate import ( "fmt"
Struct validation with reflection in Go
reflection
struct-tags
validation
Intermediate
7 steps
rust
use std::env; use std::time::Duration; #[derive(Debug, Clone)]
Loading typed config from environment variables in Rust
configuration
error-handling
generics
Intermediate
7 steps
ruby
module Api module V2 class ArticlesController < Api::BaseController before_action :set_article, only: %i[show update destroy]
Building a versioned JSON API controller in Rails
rest-api
serialization
pagination
Intermediate
10 steps
python
import shutil import uuid from pathlib import Path
Safe avatar uploads in FastAPI
file-upload
validation
streaming
Intermediate
8 steps
javascript
async function copyToClipboard(text) { if (navigator.clipboard && window.isSecureContext) { try { await navigator.clipboard.writeText(text);
Copying to the clipboard with a fallback
clipboard
progressive-enhancement
dom
Intermediate
8 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.