简体   繁体   中英

Hooking into url_for with Rails 4

I'm in the process of migrating a Rails 3 app to Rails 4. For our app, we have two top level domains which we use for our English site and Japanese site. To dynamically link to the appropriate site, we were extending url_for like the following

module I18nWwwUrlFor
  def url_for(options=nil)
    if options.kind_of?(Hash) && !options[:only_path]
      if %r{^/?www} =~ options[:controller]
        options[:host] = i18n_host
      end
    end
    super
  end
end

OurApplication::Application.routes.extend I18nWwwUrlFor

Under Rails 4, this doesn't work. This is because named routes are now calling ActionDispatch::Http::URL.url_for directly, which takes options and generates a URL. Ideally I'd want to extend this url_for, but there aren't any hooks to do so, so I'm left with monkey patching using alias_method_chain. Am I missing something and is there a better way of doing this?

I used the following for a Rails 4 app with subdomains:

module UrlHelper
  def url_for(options = nil)
    if options.is_a?(Hash) && options.has_key?(:subdomain)
      options[:host] = host_with options.delete(:subdomain)
    end
    super
  end

  def host_with(subdomain)
    subdomain += '.' unless subdomain.blank?
    [ subdomain, request.domain, request.port_string ].join
  end
end

Make sure to include the helper properly in application_controller.rb, otherwise it won't work in both controllers and views.

include UrlHelper
helper UrlHelper

Specify the subdomain when you want to change it.

root_path(subdomain: 'ja')

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM