Rails - How to use a Helper Inside a Controller
My problem resolved with Option 1. Probably the simplest way is to include your helper module in your controller:
class ApplicationController < ActionController::Base
include ApplicationHelper
...
You can use
helpers.<helper>
in Rails 5+ (orActionController::Base.helpers.<helper>
)view_context.<helper>
(Rails 4 & 3) (WARNING: this instantiates a new view instance per call)@template.<helper>
(Rails 2)- include helper in a singleton class and then
singleton.helper
include
the helper in the controller (WARNING: will make all helper methods into controller actions)
Note: This was written and accepted back in the Rails 2 days; nowadays grosser's answer is the way to go.
Option 1: Probably the simplest way is to include your helper module in your controller:
class MyController < ApplicationController
include MyHelper
def xxxx
@comments = []
Comment.find_each do |comment|
@comments << {:id => comment.id, :html => html_format(comment.content)}
end
end
end
Option 2: Or you can declare the helper method as a class function, and use it like so:
MyHelper.html_format(comment.content)
If you want to be able to use it as both an instance function and a class function, you can declare both versions in your helper:
module MyHelper
def self.html_format(str)
process(str)
end
def html_format(str)
MyHelper.html_format(str)
end
end
Hope this helps!
In Rails 5 use the helpers.helper_function
in your controller.
Example:
def update
# ...
redirect_to root_url, notice: "Updated #{helpers.pluralize(count, 'record')}"
end
Source: From a comment by @Markus on a different answer. I felt his answer deserved it's own answer since it's the cleanest and easier solution.
Reference: https://github.com/rails/rails/pull/24866