简体   繁体   English

与Rails 4挂钩url_for

[英]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. 我正在将Rails 3应用程序迁移到Rails4。对于我们的应用程序,我们有两个顶级域,分别用于英语站点和日语站点。 To dynamically link to the appropriate site, we were extending url_for like the following 为了动态链接到适当的站点,我们扩展了url_for,如下所示

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. 在Rails 4下,这不起作用。 This is because named routes are now calling ActionDispatch::Http::URL.url_for directly, which takes options and generates a URL. 这是因为命名路由现在正在直接调用ActionDispatch :: Http :: URL.url_for,它接受选项并生成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. 理想情况下,我想扩展此url_for,但是没有任何挂钩可做,所以我剩下的是使用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: 我将以下内容用于带有子域的Rails 4应用程序:

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. 确保在application_controller.rb中正确包含该帮助程序,否则它将在控制器和视图中均不起作用。

include UrlHelper
helper UrlHelper

Specify the subdomain when you want to change it. 要更改子域时,请指定它。

root_path(subdomain: 'ja')

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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