Ruby: Calling Methods Dynamically

Let’s say you have three very similar methods in your Rails app:

class Clown
 def do_something_one(foo, baz)
 end

 def do_something_two(foo, baz)
 end

 def do_something_three(foo, baz)
 end
end

You also have a slew of helper methods, that call each method, and do something else with the foo & baz objects (like serialize and log them to a DB, for example).

I had googled around a while for a way to instead just have one helper method:

 def do_something_generic(which_thing = 'one', foo, baz)
    # Dynimcally call one of the three methods,
    #    based on the 'which_thing' parameter.

    # Are any Ruby mavens in da house?  Is this right? :
    c = Clown.new
    c.send 'do_something_#{which_thing}', foo, baz

 end

How to Call Methods Dynamically in Ruby

You can Bookmark this entry on del.icio.usbookmark this, digg this entrydigg this or check the See this page in technoraticosmos

Shanti A. Braford blogs here.

If you really want to know, just read this.



  

Powered by FeedBlitz