跳至内容 跳至搜索

Action Controller UrlFor

url_for 包含到宿主类中。该类必须通过实现 _routes 方法提供一个 RouteSet。否则,将引发异常。

除了 AbstractController::UrlFor 之外,该模块还访问 HTTP 层以定义 URL 选项,例如 host。为此,该模块要求宿主类实现 env,该 env 必须与 Rack 兼容,以及 request,该 request 返回一个 ActionDispatch::Request 实例。

class RootUrl
  include ActionController::UrlFor
  include Rails.application.routes.url_helpers

  delegate :env, :request, to: :controller

  def initialize(controller)
    @controller = controller
    @url        = root_path # named route from the application.
  end
end
方法
N
U
包含的模块

类公有方法

new(...)

# File actionpack/lib/action_controller/metal/url_for.rb, line 32
def initialize(...)
  super
  @_url_options = nil
end

实例公有方法

url_options()

# File actionpack/lib/action_controller/metal/url_for.rb, line 37
def url_options
  @_url_options ||= {
    host: request.host,
    port: request.optional_port,
    protocol: request.protocol,
    _recall: request.path_parameters
  }.merge!(super).freeze

  if (same_origin = _routes.equal?(request.routes)) ||
     (script_name = request.engine_script_name(_routes)) ||
     (original_script_name = request.original_script_name)

    options = @_url_options.dup
    if original_script_name
      options[:original_script_name] = original_script_name
    else
      if same_origin
        options[:script_name] = request.script_name.empty? ? "" : request.script_name.dup
      else
        options[:script_name] = script_name
      end
    end
    options.freeze
  else
    @_url_options
  end
end