使用基于挂载引擎的url_fo获取基于约束的url



在行动调度路由过程中,有什么方法可以让url_fo根据request.host返回url吗?

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

示例:

当用户在example.com主机上时

collabore_path=>/apps/collaborate

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

collabore_path=>/apps/worktogether

经过大量的研究,我意识到RouteSet类有named_routes,它没有考虑返回url的约束。

我已经尝试在action_dispatch/routing/route_set.rb中重写@set以从rails应用程序中拾取,但无法按预期工作

@search_set = Rails.application.routes.set.routes.select{|x| x.defaults[:host] == options[:host] }[0]
@set = @search_set unless @search_set.blank?

Remove.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-限制

至于我关心的问题,如果你在中间件级别处理它,那就很好了。这就是我的设想。

config/application.rb中添加此行

config.middleware.insert_before ActionDispatch::ParamsParser, "SelectiveStack"

在应用程序目录中添加中间件,将中间件目录作为约定

app/middleware/selective_stack.rb

class SelectiveStack
  def initialize(app)
    @app = app
  end
  def call(env)
    debugger
    if env["SERVER_NAME"] == "example.com"
      "/apps/collaborate"
    else
      "/apps/worktogether"
    end
  end

end

希望这能解决你的问题。!!!

好吧,这是在黑暗中拍摄的;也许你已经试过了,也许我真的错过了什么。从表面上看,您实际上只是想覆盖apps的路径辅助方法。那么,为什么不在application_helper.rb中设置一个覆盖呢?类似于:

module ApplicationHelper
  def collaborate_path
    if request.domain == "example.com"
      "/apps/collaborate"
    else
      "/apps/worktogether"
    end
  end
end

相关内容

  • 没有找到相关文章

最新更新