基于已安装的引擎,使用url_for获取基于约束的url

Viv*_*ara 10 ruby ruby-on-rails actiondispatch ruby-on-rails-4

有什么办法可以让url_for在动作调度路由期间根据request.host返回url?

mount Collaborate::Engine => '/apps/collaborate', :constraints => {:host => 'example.com' }
mount Collaborate::Engine => '/apps/worktogether'
Run Code Online (Sandbox Code Playgroud)

例:

当用户在example.com主机上时

collaborate_path =>/apps/collaborate

当用户在任何其他主机上时

collaborate_path =>/apps/worktogether

经过大量的研究,我意识到RouteSet类有name_routes,它不考虑返回url的约束.

我已经尝试在action_dispatch/routing/route_set.rb中覆盖@set以从rails应用程序中取出但是dint按预期工作

@search_set = Rails.application.routes.set.routes.select{|x| x.defaults[:host] == options[:host] }[0]
@set = @search_set unless @search_set.blank?
Run Code Online (Sandbox Code Playgroud)

Lau*_*ens 7

在您的示例中删除.com

mount Collaborate::Engine => '/apps/collaborate', :constraints => {:host => 'examplesite' }
mount Collaborate::Engine => '/apps/worktogether'
Run Code Online (Sandbox Code Playgroud)

应该工作

如果您需要更高级的约束,请创建自己的约束:

class CustomConstraint
  def initialize
    # Things you need for initialization
  end

  def matches?(request)
    # Do your thing here with the request object
    # http://guides.rubyonrails.org/action_controller_overview.html#the-request-object
    request.host == "example"
  end
end

Rails.application.routes.draw do
  get 'foo', to: 'bar#baz',
    constraints: CustomConstraint.new
end
Run Code Online (Sandbox Code Playgroud)

您还可以将约束指定为lambda:

Rails.application.routes.draw do
  get 'foo', to: 'foo#bar',
    constraints: lambda { |request| request.remote_ip == '127.0.0.1' }
end
Run Code Online (Sandbox Code Playgroud)

来源:http://guides.rubyonrails.org/routing.html#advanced-constraints


nea*_*lob 1

好吧,这是在黑暗中拍摄的;也许你已经尝试过,或者也许我真的错过了一些东西。从表面上看,您确实看起来只是想重写apps. 那么为什么不在 中设置覆盖呢application_helper.rb?就像是:

module ApplicationHelper
  def collaborate_path
    if request.domain == "example.com"
      "/apps/collaborate"
    else
      "/apps/worktogether"
    end
  end
end
Run Code Online (Sandbox Code Playgroud)