while I realize your are supposed to use a helper inside a view, I need a helper in my controller as I'm building a JSON object to return.
It goes a little like this:
def xxxxx
@comments = Array.new
@c_comments.each do |comment|
@comments << {
:id => comment.id,
:content => html_format(comment.content)
}
end
render :json => @comments
end
how can I access my html_format
helper?
Note: This was written and accepted back in the Rails 2 days; nowadays grosser's answer (below) 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
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
...
In general, if the helper is to be used in (just) controllers, I prefer to declare it as an instance method of class ApplicationController
.
class MyController < ApplicationController
# include your helper
include MyHelper
# or Rails helper
include ActionView::Helpers::NumberHelper
def my_action
price = number_to_currency(10000)
end
end
In Rails 5+ simply use helpers (helpers.number_to_currency(10000))
In Rails 5+ you can simply use the function as demonstrated below with simple example:
module ApplicationHelper
# format datetime in the format #2018-12-01 12:12 PM
def datetime_format(datetime = nil)
if datetime
datetime.strftime('%Y-%m-%d %H:%M %p')
else
'NA'
end
end
end
class ExamplesController < ApplicationController
def index
current_datetime = helpers.datetime_format DateTime.now
raise current_datetime.inspect
end
end
OUTPUT
"2018-12-10 01:01 AM"