Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
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]
- Loading branch information
Showing
3 changed files
with
36 additions
and
1 deletion.
There are no files selected for viewing
19 changes: 19 additions & 0 deletions
19
activerecord/lib/active_record/attribute/user_provided_default.rb
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -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 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
a6e3cda
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Can the proc call instance method without receiver?
It's not clear with current test
a6e3cda
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
No, the proc doesn't get
instance_eval
ed, as it's meant to be a class level default. You should useafter_initialize
if you need more complex behavior.a6e3cda
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Hi @sgrif , I know it's an old commit but thanks to it I just realized we can't use instance method in the proc call :) Maybe it would be worth putting it in the documentation