当前位置:  开发笔记 > 后端 > 正文

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

如何解决《基于已安装的引擎,使用url_for获取基于约束的url》经验,为你挑选了1个好方法。

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

mount Collaborate::Engine => '/apps/collaborate', :constraints => {:host => 'example.com' }
mount Collaborate::Engine => '/apps/worktogether'

例:

当用户在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?

Laurens.. 7

在您的示例中删除.com

mount Collaborate::Engine => '/apps/collaborate', :constraints => {:host => 'examplesite' }
mount Collaborate::Engine => '/apps/worktogether'

应该工作

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

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

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

Rails.application.routes.draw do
  get 'foo', to: 'foo#bar',
    constraints: lambda { |request| request.remote_ip == '127.0.0.1' }
end

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



1> Laurens..:
在您的示例中删除.com
mount Collaborate::Engine => '/apps/collaborate', :constraints => {:host => 'examplesite' }
mount Collaborate::Engine => '/apps/worktogether'

应该工作

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

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

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

Rails.application.routes.draw do
  get 'foo', to: 'foo#bar',
    constraints: lambda { |request| request.remote_ip == '127.0.0.1' }
end

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

推荐阅读
云聪京初瑞子_617
这个屌丝很懒,什么也没留下!
DevBox开发工具箱 | 专业的在线开发工具网站    京公网安备 11010802040832号  |  京ICP备19059560号-6
Copyright © 1998 - 2020 DevBox.CN. All Rights Reserved devBox.cn 开发工具箱 版权所有