0

In a controller there is a code

  def action1
    generic_call __method__
  end

  def action2
    generic_call __method__
  end

  #......
  def action_n
    generic_call __method__
  end

 private

 def generic_call method_name
   #..........
 end

To get rid off repeating, would it be better to generate actions dynamically? Would it be more costly compared to static definition? How can I do that?

3
  • Without knowing anything about what the actions actually are, it's impossible to answer if it'd be a good idea or not. If you literally have actions named action1 action2 up to actionn then I'd suggest something else has already gone wrong, and I'd wonder why you're not just using a parameter. I'd also wonder why you've eschewed semantically-meaningful actions, but that's a different issue. Commented Apr 14, 2013 at 12:45
  • There is nothing wrong, they are ajax actions. Well, maybe something is wrong. Commented Apr 14, 2013 at 12:58
  • That they're Ajax actions isn't relevant, AFAICT. Commented Apr 14, 2013 at 13:17

1 Answer 1

2

The major cost is actually having to repeat all the code yourself, remember that the philosophy on rails is DRY (Don't repeat yourself).

If there is an overhead at all by defining the methods with metaprogramming, you won't notice it at all, you can however run some benchmarks yourself just to be sure, but even the rails source code is full of metaprogramming and dynamic methods all over the place, in special with ActiveRecord.

class MyController < ActionController::Base
  [:action1, :action2, :action3].each do |method_name|
    send :define_method, method_name do
      generic_call __method__
    end
  end
end
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.