Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

an inline proc/lambda typecaster executes in the instance context #187

Open
wants to merge 2 commits into
base: master
Choose a base branch
from

Conversation

dmgr
Copy link

@dmgr dmgr commented Oct 4, 2021

When using an inline proc/lambda typecaster it should be run in the context of the object thus you can use its methods.
In short we binds typecaster to the object.

@cgriego
Copy link
Owner

cgriego commented Oct 12, 2021

@dmgr Do you have an example use case for this? I'm trying to wrap my head around why this would be desirable, especially since this isn't something that I know to be supported in ROM/dry-types, ActiveRecord, Mongoid, etc.

@dmgr
Copy link
Author

dmgr commented Oct 20, 2021

The usecase is similar to default: option behavior:

when default.respond_to?(:call) then instance_exec(&default)

By the way, the:

    when default.respond_to?(:call) then instance_exec(&default)

should be

    when default.is_a?(Proc) then instance_exec(&default)

in my opinion as you can only use procs/lambdad in instance_exec and not and object with a .call method, otherwise you will get an error:

wrong argument type Xxx (expected Proc) (TypeError)

If you really want to use a #call method of the object, you should rather do:

    when default.is_a?(Proc) then instance_exec(&default)
    when default.respond_to?(:call) then instance_exec(&default.method(:call))

but I discourage doing so as it may have unpredictable side-effect depends on how default object is implemented. It would be more safe to execute only procs/lambdas in the context of attributes object, but not objects that implements #call method. So the final code snippet for lib/active_attr/attribute_defaults.rb#L114 would be:

    when default.is_a?(Proc) then instance_exec(&default)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

None yet

2 participants