Rails Helpers and default behavior

By Default all helpers are included in all views in Rails.

So your UsersHelper methods are available in views of other controller lets say your ProductsController views. So if you wanted to change the default behavior, You need to make a small change in inside config/application.rb
config.action_controller.include_all_helpers = false

ApplicationHelper is still included in all views. ProductsHelper is only included in ProductsHelper views. If that controller inherits from BaseController, then BaseHelper will be included as well.

And here’s is one more trick that you can use

For example, We like to have a LayoutHelper that the application layout template can use:


module LayoutHelper
  def layout_helper_method
    "Some layout logic"


module ApplicationHelper
  include LayoutHelper
  def global_helper_method
    "Some application logic"

With include_all_helpers off, the LayoutHelper isn’t automatically included everywhere. But by including it in the global ApplicationHelper, its methods are global and available everywhere.

By this way you get the benefits of splitting helpers into multiple separate  files, without the downsides of having every helper available everywhere.


Popular posts from this blog

Inserting and Moving elements inside Ruby Array

Find duplicate records in ServiceNow