Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Guidelines for calling controller methods in helper modules?

Few questions:

  1. Is it possible to call a controller method in a helper module (e.g., application helper)?

  2. If so, how does the helper handle the rendering of views? Ignore it?

  3. In what instances would you want to call a controller method from a helper? Is it bad practice?

  4. Do you have any sample code where you're calling controller methods in helper?

like image 357
keruilin Avatar asked May 26 '10 01:05

keruilin


People also ask

Can we call controller method in Helper?

You generally don't call controller-methods from helpers. That is: if you mean a method that collects data and then renders a view (any other method that needs to be called should probably not be in a controller). It is definitely bad practice and breaks MVC.

How do you call a helper method?

To call another function in the same helper, use the syntax: this. methodName , where this is a reference to the helper itself. For example, helperMethod2 calls helperMethod3 with this code.

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.

Where do I put controller helper?

If you're looking to write custom helper methods, the correct directory path is app/helpers . You write your helpers inside a helper module. Every Rails application comes with a base helper module by default, it's called ApplicationHelper .


2 Answers

You generally don't call controller-methods from helpers. That is: if you mean a method that collects data and then renders a view (any other method that needs to be called should probably not be in a controller). It is definitely bad practice and breaks MVC.

It is, however, perfectly possible to make controller-methods available in the views, a great example is for instance the current_user method.

To make a controller method available in the views, as a helper method, just do

private

def current_user
  # do something sensible here
  @current_user ||= session[:user] 
end
helper_method :current_user

Such a method is best defined in the private section, or it could be available as an action (if you a wildcard in your routing).

like image 137
nathanvda Avatar answered Sep 20 '22 15:09

nathanvda


Declare your methods on the corresponding controller

private
def method_name1
...
end

def method_name2
...
end

In the head of the controller declare

helper_method :method_name1, :method_name2

You may want to declare those methods under private state

And that's it, now you can use your method on a helper

like image 45
Alexis Avatar answered Sep 21 '22 15:09

Alexis