maeshimaの日記

メモ書きです

3.1.0.beta1の action_dispatch/url_for.rb のコメントの意訳

ActionDispatch::Routing

  • モデルとかでURLを生成したい場合は、ActionController::UrlForを見るといい。
  • 知ってると思うけど ActionController::Base#url_for はリンクを生成する。link_to や url_for は水面下で ActionController::UrlFor、特に ActionController::UrlFor#url_for を使っている。
  • 利便性のために、mailer には ActionController::UrlFor#url_for へのショートカットを提供している。mailer の中では、 url_for は ActionController::UrlFor#url_for と同じ。でも mailer は hostnameの情報を持っていないので、 :host オプションを付けてやる必要がある。
  • UrlForは named routes も扱う。モデルで使いたいときには下記のようにするといい。
class User < ActiveRecord::Base
  include Rails.application.routes.url_helpers
  def base_uri
    user_path(self)
  end
end
User.find(1).base_uri #=> "/users/1"

ActionDispatch::UrlFor#url_for

オプションの説明で気になったところだけ抜粋

subdomain
リンクのサブドメイン部を指定。tld_lengthでホストとドメインを分ける。
domain
リンクのドメインを指定。tld_lengthでホストとドメインを分ける。
tld_length
subdomainかdomainが指定したときのみ有効。デフォルトの値は ActionDispatch::Http::URL.tld_length で指定されていてデフォルトは 1。
trailing_slash
trueなら末尾にスラッシュ"/"がつく。