Skip to content

Commit

Permalink
Restore behavior for non-proc/non-method callables in defaults_setter
Browse files Browse the repository at this point in the history
Add documentation for using procs that accept arguments.

Update CHANGELOG.
  • Loading branch information
jeremyevans committed Jul 25, 2024
1 parent 980c261 commit 48f3ce6
Show file tree
Hide file tree
Showing 3 changed files with 19 additions and 3 deletions.
2 changes: 2 additions & 0 deletions CHANGELOG
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
=== master

* Have defaults_setter plugin pass model instance to default_values callable if it has arity 1 (pedrocarmona) (#2195)

* Support string_agg extension on SQLite 3.44+ (segiddins) (#2191)

* Support schema-qualified table names when using create_table :temp with a Sequel::SQL::QualifiedIdentifier (jeremyevans) (#2185)
Expand Down
12 changes: 9 additions & 3 deletions lib/sequel/plugins/defaults_setter.rb
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,12 @@ module Plugins
# Album.default_values[:a] = lambda{Date.today}
# Album.new.a # => Date.today
#
# If the proc accepts a single argument, it is passed the instance, allowing
# default values to depend on instance-specific state:
#
# Album.default_values[:a] = lambda{|album| album.b + 1}
# Album.new(b: 10).a # => 11
#
# By default, default values returned are not cached:
#
# Album.new.a.equal?(Album.new.a) # => false
Expand Down Expand Up @@ -134,10 +140,10 @@ def [](k)
if new? && !values.has_key?(k)
v = model.default_values.fetch(k){return}
if v.respond_to?(:call)
if v.arity == 1
v = v.call(self)
v = if v.respond_to?(:arity) && v.arity == 1
v.call(self)
else
v = v.call
v.call
end
end
values[k] = v if model.cache_default_values?
Expand Down
8 changes: 8 additions & 0 deletions spec/extensions/defaults_setter_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -181,6 +181,14 @@ def db.schema(*) [] end
c.new.a.must_equal 2
end

it "should support non-proc/non-method callables" do
@pr.call(2)
o = Object.new
def o.call; 3; end
@c.default_values[:a] = o
@c.new.a.must_equal 3
end

it "should allow proc default values that depend on other values" do
@pr.call(2)
@c.default_values[:a] = proc{ |instance| instance.b * 2 }
Expand Down

0 comments on commit 48f3ce6

Please sign in to comment.