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

Walkthrough

Space play step click any line
Three takeaways
  1. 1Deferring execution lets you build up a query as data and run it exactly once, on demand.
  2. 2Overriding method_missing must be paired with respond_to_missing? so the object behaves honestly under respond_to? and duck typing.
  3. 3Returning a fresh instance per call keeps each chain step immutable and side-effect free.

Related explainers

Share this explainer

Here's the card — post it anywhere.

Building a lazy query proxy in Ruby — share card
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code