Calling dynamic methods in Ruby on Rails

Posted on 11 September 2007

To utilise dynamic method names in Ruby on Rails you can use Ruby's send method to pass a message to an object.

For example:

["foo", "bar"].each do |method|
	MyClass.send(method)
end

The above is obviously a very crude example but it's the same as calling MyClass.foo and MyClass.bar.

The point is that the array could be dynamic and this means you can write code that calls methods prior to knowing what those methods may well be.

You can use send to call dynamic helper methods by just calling it on it's own.

Comments left...

  • Awesome! Thanks much!

    Bob at 14 Sep 07 at 11:17

  • Thanks for the find. You should also mention that respond_to? can verify the presence of a dynamic method. (:

    Josh at 18 Jul 08 at 08:03

  • Thanks very much, It was very helpfull for me :)

    Robin at 06 Nov 08 at 08:42

  • How to write a method which takes dynamic parameter?Please mail if solved.

    Sanjib at 20 Mar 09 at 03:47

  • To pass parameters, without knowing how wasn’t that obvious (syntaxically speaking…) :

    1. controller
      [“method1”,“method2”].each do |meth|
      MyClass.send(meth, param1, param2,…)
      end
    1. model
      def meth(param1,param2,…)

      end

    Big thx paul to have put me on the way with this post.
    , hope I did not wrote craps right here ;); worked on my side.

    Ben at 19 Sep 09 at 05:07

  • Great post here. I will be using this to build a modular web spider for various social sites.

    amusing marlow at 16 Jun 10 at 23:49

Got something to say?