Rails: クラス,モデル,モジュールなどでURLヘルパー(xxx_path, xxx_url)を利用する方法

Ruby

URLヘルパーについて

URLヘルパーxxx_pathxxx_urlの形式でアプリケーションのパスを表現できるようにしてくれるRailsのヘルパーメソッドです。

URLヘルパーはコントローラ、ヘルパー、ビュー以外の箇所(クラス、モデル、モジュールなど)ではデフォルトで利用できません。

class Example
  def say_health_path
    p health_path
    p health_url(host: 'example', protocol: 'https')
  end
end

> Example.new.say_health_path
NameError: undefined local variable or method `health_path' for #<Example:0x00007f1f79d7b7d0>

    p health_path
      ^^^^^^^^^^^
from /app/app/models/example.rb:3:in `say_health_path'

クラス、モデル、モジュールなどでURLヘルパーを利用できるようにする方法には以下の2つがあります。

方法1: 『Rails.application.routes.url_helpers』と明記する

xxx_pathではなく、Rails.application.routes.url_helpers.xxx_pathと明記することでURLヘルパーが利用できます。

class Example
  def say_health_path
    p Rails.application.routes.url_helpers.health_path
    p Rails.application.routes.url_helpers.health_url(host: 'example', protocol: 'https')
  end
end

> Example.new.say_health_path
"/health"
"https://example/health"
=> "https://example/health"

方法2: 『include Rails.application.routes.url_helpers』を追加する

include Rails.application.routes.url_helpersを追加することでxxx_pathxxx_urlが利用できます。

class Example
  include Rails.application.routes.url_helpers

  def say_health_path
    p health_path
    p health_url(host: 'example', protocol: 'https')
  end
end

> Example.new.say_health_path
"/health"
"https://example/health"
=> "https://example/health"

さいごに

Twitter(@nishina555)やってます。フォローしてもらえるとうれしいです!

参考資料