I am writing a small plugin for ruby on Rails. I faced a problem while create a common action for all the controllers. I found a solution for it, But i am not satisfied with the solution. The solution that I got is :- ActionController::Base.class_eval do def common_action render :text => "hai" end def action_init self.class.action_methods.add "common_action" end before_filter :action_init end ---- If you have any alternate solution, please provide.
on 2009-02-12 13:42
on 2009-02-12 14:07
maybe i'm completely confused about what you're trying to do, but application-controller says the following: # Filters added to this controller apply to all controllers in the application. # Likewise, all the methods added will be available for all controllers.
on 2009-02-12 14:19
MaD wrote: > maybe i'm completely confused about what you're trying to do, but > application-controller says the following: > # Filters added to this controller apply to all controllers in the > application. > # Likewise, all the methods added will be available for all > controllers. From plugin librarys, we cann't access the ApplicationController class.
on 2009-02-12 15:06
that's right, but you didn't mention you were trying to write a plugin. in that case try to write it like this: # my_plugin.rb: module MyPlugin def my_action end end # init.rb: ActionController::Base.send :include, MyPlugin hope i didn't forget anything.
on 2009-02-12 15:21
sorry, just checked it. i gotta be like this: # my_plugin.rb: module MyPlugin def self.included(base) base.extend(ClassMethods) end module ClassMethods def my_action # ... end end end irb(MyOtherController):001:0> MyOtherController.methods.include? ('my_action') => true
on 2009-02-12 15:35
> If you have any alternate solution, please provide. I didn't go the plugin route in our application, but opted for a form of "behavior by convention" class GenericController < ApplicationController # here's the standard index method def index blah blah blah end # here's a new common method for all controllers def common_action moo moo moo end end class Project < GenericController # inherits the "common_action" action # and if need be (if Project truly needs behavior different from # the 'standard' we have for our app def index # non-standard behavior for this class blah blah blah end end