Topic: how can I get the function name from a variable?

hey all,

is there a way to do something like this:

myobject=Myobject.new
x='mydef'
@y=myobject.x

thanx in advance

Pat

Last edited by patcito (2007-05-15 21:08:11)

Re: how can I get the function name from a variable?

Not sure what you're asking.  If you're asking how to run a method based on a certain variable that had been set, I think you need to use eval(), like so:

myobject = MyObject.new
x = 'mydef'
@y = eval("myobject.#{x}")

There's probably a more elegant solution.  I'll check.

Edit
Of course, with Ruby there's always a more elegant solution:

myobject = Myobject.new
x = 'mydef'
@y = myobject.send(x)

Last edited by Firanide (2007-05-15 22:25:50)

Re: how can I get the function name from a variable?

ok, thanx a lot.
Any idea how to do the same with the class name?
such as:

c='Myclass'
@myobject=c.new

thanx in advance

Edit:
Found it:

 c = Myclass
obj = c.new
or
c = Object.const_get('MyClass')
c.new

Pat

Last edited by patcito (2007-05-16 15:24:23)

Re: how can I get the function name from a variable?

There's also:

'MyClass'.constantize

Railscasts - Free Ruby on Rails Screencasts

Re: how can I get the function name from a variable?

Thanx again.
By the way is it secure to pass class and function as variable in rails?
if I use a link that has params such as :classname=>'Myclass'
and then in my controller doing something like Myclass.new or Myclass.destroy?

Re: how can I get the function name from a variable?

Depends what you are doing with it. You have to be more careful with function names than class names, but security needs to be taken into account for both. They can't insert full out Ruby code, but they can change the name of the class/function to something else and this can lead to improper behavior.

If you only plan to accept a select few kinds of input, it's best to make sure the input matches one of these before using it.

Railscasts - Free Ruby on Rails Screencasts