views:

39

answers:

2

Hi All,

I have the following scenario

I want to add methods dynamically to a controller. All my method names are in a table . Please refer the following example

-table (method_names)-

1 - Walk
2 - Speek
3 - Run

and I have a controller

class UsersController < ApplicationController

   def index

   end 

end

Inside this index action i want to call my methods dynamically. Those methods were actually implemented else ware.

I have another controller like

class ActionImplementController < ApplicationController

   def walk
     puts "I'm walking"
   end 

   def speek
     puts "I'm sppeking"
   end 

   def run
     puts "I'm running"
   end 


end  

** I have done something like below and its working

class UsersController < ApplicationController

   def index
     a = eval("ActionImplementController.new.run")
   end 

end

But my question is , is this the right way or is there anyother way to do this

Thanks in advance

cheers

sameera

+1  A: 

I think it's generally best to avoid the use of eval. If you can, I would make all your methods class methods and then run them like so:

def index
    ActionImplementController.send :run
    # ActionImplementController.new.send(:run) works if you can't use class methods
end
cam
hi camthanks for the quick reply - could you please explain how to pass parameters for the above :run methodsameera
sameera207
just add them to the send call: `Foo.send :method, arg1, arg2, ..., argN`. Also see http://ruby-doc.org/core/classes/Object.html#M000332
cam
Hi cam,Works, thanks a lotcheerssameera
sameera207
+2  A: 

While the first answer works, i would prefer something like this

module ImplementsActions
  def run
    ...
  end

  def walk
    ..
  end

  def ...
end

and then in your controller write

class UsersController < ActionController::Base

  include ImplementsActions

  # now you can just use run/speek/walk

  def index
    run
  end
end

Much cleaner because the code can be shared, but it is defined where you need it.

nathanvda