【问题标题】:default_url_options for Routes Specified in Rails EngineRails 引擎中指定的路由的 default_url_options
【发布时间】:2015-02-12 13:48:42
【问题描述】:

我有一个 Rails 3.2.x 应用程序,它有两个主要引擎,使用 this configuration 处理来自两个不同域的请求:

Company::Application.routes.draw do
  constraints host: ENV['DOMAIN_ONE'] do
    mount Core::Engine, :at => '/'
  end

  constraints host: ENV['DOMAIN_TWO'] do
    mount Another::Engine, at: '/'
  end
end

我需要从Core::Engine中的页面引用Another::Engine中的路由,例如:

<%= link_to "A Link", another.a_route_url %>

但是,当我的 URL 辅助方法没有生成域为 Another::Engine 的完整 URL 时;相反,助手使用Core::Engine 的域。

我猜default_url_options 会自动设置在Rails::Engine 代码内部的某个位置,并根据引擎的路由约束自动设置host 选项。我的预感是当 any 帮助器在该引擎内的操作中被调用时——即使它是另一个引擎中的 URL 帮助器——帮助器继承当前引擎的 default_url_options。

有没有办法强制在另一个引擎中指定的所有路由使用不同的host 参数而不将host 参数直接传递给助手(即another.a_route_url(host: ENV['DOMAIN_TWO']))?

【问题讨论】:

  • 如果我理解正确,您无法使用 engine.named_route 的建议做法,因为它也与安装在根目录的其他引擎冲突?例如,当安装引擎时,引擎路由可以在 _engine.new_sessions_path 下访问。最近在创建引擎时查看了所有这些,Rails 路由存在于 Rails.application.routes (RouteSet) 上。我不知道这是否有很大帮助。
  • 不,我使用 another.route_url 很好,但返回的完整 URL 使用当前引擎的 host,而不是 routes 中为 another 引擎指定的 host /跨度>
  • 还有成功吗?你可以在 Rails 引擎中使用初始化器吗?

标签: ruby-on-rails ruby ruby-on-rails-3 routing


【解决方案1】:

对此进行了调查,这是我能找到的最佳解决方案:

# engine_route_modifier.rb
class EngineRouteModifier
  def initialize(proxy, opts = {})
    @options = opts
    @proxy = proxy
  end

  def method_missing(method_sym, *arguments, &block)
    extracted_url_options = arguments.extract_options!

    @options.each do |k,v|
      if !extracted_url_options.has_key?(k)
        extracted_url_options[k] = v
      end
    end

    arguments << extracted_url_options

    @proxy.send(method_sym, *arguments)
  end
end

# application_helper.rb
module ApplicationHelper
  def core_proxy
    @core_proxy ||= EngineRouteModifier.new(core, host: ENV['DOMAIN_ONE'])
  end

  def another_proxy
    @another_proxy ||= EngineRouteModifier.new(another, host: ENV['ANOTHER_DOMAIN'])
  end
end

【讨论】:

    猜你喜欢
    • 2013-06-16
    • 1970-01-01
    • 2017-08-13
    • 1970-01-01
    • 1970-01-01
    • 2012-08-16
    • 1970-01-01
    • 2011-08-25
    • 1970-01-01
    相关资源
    最近更新 更多