diff options
author | Sean Griffin <sean@thoughtbot.com> | 2015-05-28 16:26:49 -0600 |
---|---|---|
committer | Sean Griffin <sean@thoughtbot.com> | 2015-05-28 16:26:49 -0600 |
commit | a6e3cdae0ce1d05a6b9f7dff4499f6be3fbf63c2 (patch) | |
tree | f9b27900741eaf94b2e09b8a156e5475edd127e3 /activerecord/lib | |
parent | 73aab036eeeb297dc85dc812f54e26aa943f48f7 (diff) | |
download | rails-a6e3cdae0ce1d05a6b9f7dff4499f6be3fbf63c2.tar.gz rails-a6e3cdae0ce1d05a6b9f7dff4499f6be3fbf63c2.tar.bz2 rails-a6e3cdae0ce1d05a6b9f7dff4499f6be3fbf63c2.zip |
Allow proc defaults with the Attributes API
This is a variant implementation of the changes proposed in #19914.
Unlike that PR, the change in behavior is isolated in its own class.
This is to prevent wonky behavior if a Proc is assigned outside of the
default, and it is a natural place to place the behavior required by #19921
as well.
Close #19914.
[Sean Griffin & Kir Shatrov]
Diffstat (limited to 'activerecord/lib')
-rw-r--r-- | activerecord/lib/active_record/attribute/user_provided_default.rb | 19 | ||||
-rw-r--r-- | activerecord/lib/active_record/attributes.rb | 8 |
2 files changed, 26 insertions, 1 deletions
diff --git a/activerecord/lib/active_record/attribute/user_provided_default.rb b/activerecord/lib/active_record/attribute/user_provided_default.rb new file mode 100644 index 0000000000..29d37ac689 --- /dev/null +++ b/activerecord/lib/active_record/attribute/user_provided_default.rb @@ -0,0 +1,19 @@ +require 'active_record/attribute' + +module ActiveRecord + class Attribute # :nodoc: + class UserProvidedDefault < FromUser + def initialize(name, value, type) + super(name, value, type) + end + + def type_cast(value) + if value.is_a?(Proc) + super(value.call) + else + super + end + end + end + end +end diff --git a/activerecord/lib/active_record/attributes.rb b/activerecord/lib/active_record/attributes.rb index 50339b6f69..e574aebd6c 100644 --- a/activerecord/lib/active_record/attributes.rb +++ b/activerecord/lib/active_record/attributes.rb @@ -1,3 +1,5 @@ +require 'active_record/attribute/user_provided_default' + module ActiveRecord # See ActiveRecord::Attributes::ClassMethods for documentation module Attributes @@ -236,7 +238,11 @@ module ActiveRecord if value == NO_DEFAULT_PROVIDED default_attribute = _default_attributes[name].with_type(type) elsif from_user - default_attribute = Attribute.from_user(name, value, type) + default_attribute = Attribute::UserProvidedDefault.new( + name, + value, + type, + ) else default_attribute = Attribute.from_database(name, value, type) end |