Reputation: 600
I have some code stored in a string and I want to run it in the context of a specific record.
I want to do something like this:
class Dog < ActiveRecord::Base
# has the attributes name and age
end
a_dog = Dog.first
some_code = "puts name"
eval some_code, a_dog.get_binding
That would print the first dogs' name. I know the get_binding
method isn't right but I think the name demonstrates what I want to do.
Also, I know I shouldn't do this, I just want to know if there's a way I can :)
Upvotes: 0
Views: 65
Reputation: 4245
You can use instance_eval method which evaluates a code string within the context of the receiver.
a_dog = Dog.first
a_dog.instance_eval('puts name')
snuppy
=> nil
Upvotes: 3