Skip to content

Commit 18f1ce7

Browse files
committed
Add allow_by_default option for forbid_lazy_load plugin
This one was conceived and discussed more thoroughly over in #2286. The basic idea is that the `forbid_lazy_load` plugin disables lazy loading on specific model instances, but also broadly on any models loaded through an association. The latter can be detrimental when trying to cut over to eager loading incrementally and where it's hard to get an entire codebase converted all at once. Here, the `forbid_lazy_load` plugin picks up a new `allow_by_default` option. When it's set to true, lazy loading can still be forbidden normally on an instance-by-instance basis, but it's not forbidden through associations. This should make incremental migrations to eager loading with `forbid_lazy_load` somewhat easier to do.
1 parent ffb9e28 commit 18f1ce7

File tree

3 files changed

+322
-254
lines changed

3 files changed

+322
-254
lines changed

CHANGELOG

+2
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,8 @@
66

77
* Support treat_string_list_as_untyped_array Database option in pg_auto_parameterize_in_array extension (jeremyevans)
88

9+
* Support allow_by_default option in forbid_lazy_load extension (brandur) (#2288)
10+
911
=== 5.90.0 (2025-03-01)
1012

1113
* Avoid one query per enum when loading pg_enum extension when pg_array extension is already loaded (nick96) (#2278, #2279)

lib/sequel/plugins/forbid_lazy_load.rb

+14-1
Original file line numberDiff line numberDiff line change
@@ -39,6 +39,9 @@ module Plugins
3939
#
4040
# Album.first.artist # no error
4141
#
42+
# This behavior of enabling +forbid_lazy_load+ automatically from dataset
43+
# methods can be disabled using the plugin's +:allow_by_default+ option:
44+
#
4245
# You can allow lazy loading associations for an instance that it
4346
# was previously forbidden for:
4447
#
@@ -98,7 +101,17 @@ module Plugins
98101
#
99102
# # Make the Album class support forbidding lazy load
100103
# Album.plugin :forbid_lazy_load
104+
#
105+
# # Let lazy loading be forbidden by object, but not automatically for any
106+
# # object loaded via dataset.
107+
# Album.plugin :forbid_lazy_load, allow_by_default: true
101108
module ForbidLazyLoad
109+
def self.apply(model, opts=OPTS)
110+
unless opts[:allow_by_default]
111+
model.send(:dataset_extend, ForbidByDefault, :create_class_methods=>false)
112+
end
113+
end
114+
102115
# Error raised when attempting to lazy load an association when
103116
# lazy loading has been forbidden.
104117
class Error < StandardError
@@ -179,7 +192,7 @@ def _load_associated_objects(opts, dynamic_opts=OPTS)
179192
end
180193
end
181194

182-
module DatasetMethods
195+
module ForbidByDefault
183196
# Mark model instances retrieved in this call as forbidding lazy loading.
184197
def each
185198
if row_proc

0 commit comments

Comments
 (0)