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
ruby
class BackfillUsersFullName < ActiveRecord::Migration[7.1] disable_ddl_transaction! BATCH_SIZE = 5_000
How to backfill a column safely in Rails
migrations
batching
backfill
Intermediate
7 steps
ruby
class ProjectsController < ApplicationController def new @project = current_account.projects.build load_form_collections
The new/create pattern in a Rails controller
mvc
strong-parameters
tenant-scoping
Intermediate
7 steps
go
type CreateUserInput struct { Name string `json:"name" binding:"required,min=2,max=64"` Email string `json:"email" binding:"required,email"` Password string `json:"password" binding:"required,min=8"`
Turning Gin validation errors into JSON
validation
request-binding
error-handling
Intermediate
9 steps
javascript
const express = require('express'); const { createProxyMiddleware, fixRequestBody } = require('http-proxy-middleware'); const router = express.Router();
Building an API gateway proxy in Express
reverse-proxy
middleware
api-gateway
Intermediate
6 steps
rust
use axum::{ extract::{FromRequestParts, Query}, http::{request::Parts, StatusCode}, };
Building a custom Axum extractor for query filters
extractors
query-parsing
enums
Intermediate
8 steps
python
import asyncio from dataclasses import dataclass import aiohttp
Bounded-concurrency HTTP fetching with asyncio
async
concurrency
semaphore
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.