Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby on Rails: Global Helper method for all controllers

How do I set up a method that I want accessible from all controllers?

Sticking the method in application_helper just makes it available to the views

like image 503
DerNalia Avatar asked Jun 17 '10 15:06

DerNalia


People also ask

Can we use helper method in controller rails?

In Rails 5, by using the new instance level helpers method in the controller, we can access helper methods in controllers.

How do you use the helper method in Ruby on Rails?

A Helper method is used to perform a particular repetitive task common across multiple classes. This keeps us from repeating the same piece of code in different classes again and again. And then in the view code, you call the helper method and pass it to the user as an argument.

Where do I put controller helper?

If you need to use a method in the application scope then I would suggest that you keep those methods inside the application controller and in order to use them inside views.. declare those as helper methods. The problem is that if there are many helper methods, ApplicationController can become unwieldy.


2 Answers

You can add the method to ApplicationController. All the other controllers subclass ApplicationController, so will be able to call the method.

You'll want to make the method protected so that it is only visible to subclasses and isn't available as a web-accessible action.

like image 84
Phil Ross Avatar answered Sep 28 '22 06:09

Phil Ross


You can include ApplicationHelper in your controllers (or base ApplicationController) to make the helper methods available.

You can also include the following line in your ApplicationController to include all helpers:

helper :all
like image 18
elektronaut Avatar answered Sep 28 '22 06:09

elektronaut