All,
I have a view component that I would like to generalize.
What are the practical differences (if any) between using
@object.send(‘xyz’)
and
eval("@object.xyz")
to dynamically get at an object’s attributes?
Thanks,
Wes
All,
I have a view component that I would like to generalize.
What are the practical differences (if any) between using
@object.send(‘xyz’)
and
eval("@object.xyz")
to dynamically get at an object’s attributes?
Thanks,
Wes
Wes G. wrote:
eval(“@object.xyz”)
to dynamically get at an object’s attributes?
Thanks,
Wes
Short answer: The first is much better from a security point of view
(image what @object.xyz could contain). If send doesn’t have enough
functionality, investigate instance_eval:
http://corelib.rubyonrails.org/classes/Object.html#M001079
In this particular case, I’m just using the eval to get at attributes of
an object, so I have complete control over what is getting “eval”'ed.
The reason I want to use eval is if I want to get at an attribute that
is embedded in a subordinate object.
I can specify that with x.y.z.attr and eval it
instead of
x.send(y).send(z).send(attr) or
x.instance_eval { @y.send(z).send(attr) } or other more verbose ways of
expressing “go get this attribute from somewhere in the object graph”.
Wes
Another option could be do define the [] method on the object to return
the
result of running that method.
class MyClass
def
send(method)
end
end
That would make it less verbose:
x[y][z][attr]
But if you are 100% sure that what is being passed to eval is completely
safe, then using eval shouldn’t be a problem.
-Jonathan
This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.
Sponsor our Newsletter | Privacy Policy | Terms of Service | Remote Ruby Jobs