(Rails) Controller 等で helper を呼ぶ方法
Published: 2023/6/15
Rails - How to use a Helper Inside a Controller
While I realize you 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...
stackoverflow.com

上記の通り、 rails 5 以上では、以下のようにすると呼べる。
# app/helpers/hoge_helper.rb
class HogeHelper
def times_two(n)
n * 2
end
end
# app/controllers/some_controller.rb
class SomeController
def index
@num = helpers.times_two(2)
end
end
# lib/tasks/hoge.rake; controller 以外の場所で呼ぶ
task :hoge_task do
puts ApplicationController.helpers.times_two(2)
end
Tags: rails
関連記事
Rails の view では、相対パス(キー)のロケールが使える
2023/9/7
factory_bot と必須 association
2023/4/23
Rails とタイムゾーン
2023/4/19