目次
URLヘルパーについて
URLヘルパーはxxx_path
、xxx_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_path
やxxx_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)やってます。フォローしてもらえるとうれしいです!