url_for.rb 1.3 KB
Newer Older
1 2 3 4 5
# Includes #url_for into the host class. The class has to provide a RouteSet by implementing 
# the #_routes methods. Otherwise, an exception will be raised.
#
# In addition to AbstractController::UrlFor, this module accesses the HTTP layer to define 
# url options like the +host+. In order to do so, this module requires the host class
6 7 8 9 10 11 12 13 14 15 16 17 18
# to implement #env and #request, which need to be a Rack-compatible.
#
# Example:
#
#   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
19 20 21 22
module ActionController
  module UrlFor
    extend ActiveSupport::Concern

23
    include AbstractController::UrlFor
24

25
    def url_options
26
      @_url_options ||= super.reverse_merge(
27 28
        :host => request.host,
        :port => request.optional_port,
29 30 31 32 33 34
        :protocol => request.protocol,
        :_path_segments => request.symbolized_path_parameters
      ).freeze

      if _routes.equal?(env["action_dispatch.routes"])
        @_url_options.dup.tap do |options|
35
          options[:script_name] = request.script_name.dup
36
          options.freeze
37
        end
38 39
      else
        @_url_options
40
      end
41
    end
42

43
  end
44
end