Helpers available both in controller and templates

With famous DRY, I have written a bunch of common checks from RNS to some helpers methods. And I have to find some way to access them both from templates (RHTML) and controllers.

Rails provides two places to hold common helpers. First is app/controllers/application.rb, parent for all controllers. Methods defined in this class will be accessible for all controllers in Your application. Second one place is app/helpers/application_helper.rb. Methods defined there will be accessible for all RHTML templates.

But I see no simple way to write this in one place. Well it could be placed somewhere in lib directory and included by environments.rb, but I’m not sure if changes in such code would be automatically reloaded in development mode.

Methods from controllers can be accessed from template via controller variable (like this: controller.isOwner(@route)), but this is too verbose. So for now I use following approach – I define real code in ApplicationController (app/controllers/application.rb) and in appplication_helper.rb I define simple wrapper for each method I have defined in ApplicationController:

def isOwner(rt)
   controller.isOwner(rt)
end

Leave a comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.