View: @object.send('method') vs. eval("@object.method")

Wes Gamble wrote:

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

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

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