ruby
40 lines · 7 steps
Building a lazy query proxy in Ruby
A proxy records chainable query calls and replays them against a relation only when results are actually needed.
Explained by
highlit
1class QueryProxy
2 ALLOWED = %i[where limit offset order includes distinct].freeze
3
4 def initialize(relation, operations = [])
5 @relation = relation
6 @operations = operations
7 end
8
9 def method_missing(name, *args, &block)
10 if ALLOWED.include?(name)
11 self.class.new(@relation, @operations + [[name, args, block]])
12 elsif @relation.respond_to?(name)
13 resolve.public_send(name, *args, &block)
14 else
15 super
16 end
17 end
18
19 def respond_to_missing?(name, include_private = false)
20 ALLOWED.include?(name) || @relation.respond_to?(name, include_private) || super
21 end
22
23 def resolve
24 @operations.reduce(@relation) do |rel, (name, args, block)|
25 rel.public_send(name, *args, &block)
26 end
27 end
28
29 def to_a
30 resolve.to_a
31 end
32
33 def each(&block)
34 resolve.each(&block)
35 end
36
37 def explain
38 @operations.map { |name, args, _| "#{name}(#{args.map(&:inspect).join(', ')})" }.join(" -> ")
39 end
40end
01 / 01
STEP 01
‹ swipe to step through ›
Walkthrough
Space play
←→ step
click any line
Three takeaways
- 1Deferring execution lets you build up a query as data and run it exactly once, on demand.
- 2Overriding method_missing must be paired with respond_to_missing? so the object behaves honestly under respond_to? and duck typing.
- 3Returning a fresh instance per call keeps each chain step immutable and side-effect free.
Related explainers
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
go
package logging import ( "context"
Deduplicating log attributes in Go's slog
decorator-pattern
structured-logging
immutability
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/building-a-lazy-query-proxy-in-ruby-explained-ruby-7c1c/embed?autoplay=1" width="100%" height="520" loading="lazy" style="border:0"></iframe>
Autoplay is on by default — add ?autoplay=0 to start paused.