You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Copy file name to clipboardExpand all lines: README.md
+22Lines changed: 22 additions & 0 deletions
Display the source diff
Display the rich diff
Original file line number
Diff line number
Diff line change
@@ -55,6 +55,17 @@ Are you not working with [ActiveRecord][5]? N1Loader is ready to be used as stan
55
55
gem 'n1_loader'
56
56
```
57
57
58
+
Want lazy, N+1-free loading without explicit preloading? Use `n1_bind_to` to share context across a collection of plain Ruby objects. ([full snippet](examples/n1_bind_to.rb))
59
+
60
+
```ruby
61
+
users = [User.new, User.new, User.new]
62
+
63
+
# Bind users to the collection — lazy access is now automatically batched
64
+
users.each { |user| user.n1_bind_to(users) }
65
+
66
+
users.map(&:optimized_call) # loads all in a single batch, no N+1
67
+
```
68
+
58
69
## How to use it?
59
70
60
71
N1Loader provides DSL that allows you to define N+1 ready loaders that can
@@ -156,6 +167,7 @@ p User.all.includes(:payments_total).map { |user| user.payments_total(from: from
156
167
- Loader support [arguments](examples/arguments_support.rb)
157
168
- Has [integration](examples/active_record_integration.rb) with [ActiveRecord][5] which makes it brilliant
158
169
- Has [integration](examples/ar_lazy_integration.rb) with [ArLazyPreload][6] which makes it excellent
170
+
- Supports [context sharing](examples/n1_bind_to.rb) for plain Ruby objects without ActiveRecord
159
171
160
172
### Feature killer for [ArLazyPreload][6] integration with isolated loaders
161
173
@@ -168,6 +180,16 @@ Without further ado, please have a look at the [example](examples/ar_lazy_integr
168
180
169
181
_Spoiler:_ as soon as you have your loader defined, it will be as simple as `Loader.for(element)` to get your data efficiently and without N+1.
170
182
183
+
### Context sharing for plain Ruby objects with `n1_bind_to`
184
+
185
+
In [version 2.1.0](CHANGELOG.md#210---20260307) context sharing was added for plain Ruby objects.
186
+
This allows you to get lazy, N+1-free loading without [ActiveRecord][5] or explicit preloading.
187
+
188
+
By calling `n1_bind_to(collection)` on each element, you bind them to their shared collection.
189
+
When any loader is triggered on a bound element, it automatically batch-loads for the entire collection — and nested loaders propagate the context automatically as well.
190
+
191
+
Have a look at the [example](examples/n1_bind_to.rb) to see how simple it is.
0 commit comments