Few questions:
Is it possible to call a controller method in a helper module (e.g., application helper)?
If so, how does the helper handle the rendering of views? Ignore it?
In what instances would you want to call a controller method from a helper? Is it bad practice?
Do you have any sample code where you're calling controller methods 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.
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.
In Rails 5, by using the new instance level helpers method in the controller, we can access helper methods in controllers.
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 .
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).
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With