Where to locate methods used by multiple Rails controllers & restricting access to the base controller
I have two co开发者_如何学运维ntrollers (say ArticlesController and PostsController) that use about 5 of the same methods. These are the only two controllers that use the 5 methods, so they don't feel like they should be located in ApplicationController. Currently, I created a base controller (say ContentController) and then the existing two controllers inherit from this base.
My question is - is this the best approach to reducing duplication?
Second question - how to I ensure that these methods are only accessed by the controllers that inherit from the base? In the example above, I don't want ContentController to be accessed directly.
Thanks!
I think having a common ancestor that ArticlesController and PostsController both inherit from is totally acceptable. That's what inheritance is for isn't it? If you don't want the actions exposed directly from ContentController, simply make sure no routes route to ContentController.
Another way of doing it would be to make a module for those functions, and include that module as needed. Let's say you want to call the module "My Functions":
/lib/my_functions.rb:
module MyFunctions
def function1
...
end
def function2
...
end
...
end
Then wherever you need those functions just include that module:
class PostsController < ActionController::Base
include MyFunctions
...
end
class ArticlesController < ActionController::Base
include MyFunctions
...
end
精彩评论