(Rails) Controller 等で helper を呼ぶ方法

Published: 2023/6/15


上記の通り、 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

関連記事