子域约束并排除某些子域

在我的routes.rb文件中,我想在routes.rb中使用子域约束function,但是我想从catch all路由中排除某些域。 我不想在特定的子域中拥有某个控制器。 这样做的最佳做法是什么。

 # this subdomain i dont want all of the catch all routes constraints :subdomain => "signup" do resources :users end # here I want to catch all but exclude the "signup" subdomain constraints :subdomain => /.+/ do resources :cars resources :stations end 

您可以在约束正则表达式中使用否定前瞻来排除某些域。

 constrain :subdomain => /^(?!login|signup)(\w+)/ do resources :whatever end 

在Rubular上尝试一下

这是我来的解决方案。

 constrain :subdomain => /^(?!signup\b|api\b)(\w+)/ do resources :whatever end 

它会匹配api不是 apis

使用edgerunner和George建议的负向前瞻是很棒的。

基本上,模式将是:

 constrain :subdomain => /^(?!signup\Z|api\Z)(\w+)/ do resources :whatever end 

这与George的建议相同,但我将\b更改为\Z – 从单词边界更改为输入字符串本身的末尾(如我对George的答案的评论中所述)。

以下是一组显示差异的测试用例:

 irb(main):001:0> re = /^(?!www\b)(\w+)/ => /^(?!www\b)(\w+)/ irb(main):003:0> re =~ "www" => nil irb(main):004:0> re =~ "wwwi" => 0 irb(main):005:0> re =~ "iwwwi" => 0 irb(main):006:0> re =~ "ww-i" => 0 irb(main):007:0> re =~ "www-x" => nil irb(main):009:0> re2 = /^(?!www\Z)(\w+)/ => /^(?!www\Z)(\w+)/ irb(main):010:0> re2 =~ "www" => nil irb(main):011:0> re2 =~ "wwwi" => 0 irb(main):012:0> re2 =~ "ww" => 0 irb(main):013:0> re2 =~ "www-x" => 0 

重温这个老问题,我只是想到了另一种方法,可以根据你想要的方式工作……

Rails路由器尝试按指定的顺序将请求与路由匹配。 如果找到匹配项, 则不检查其余路径。 在保留的子域块中,您可以对所有剩余路由进行全局化并将请求发送到错误页面。

 constraints :subdomain => "signup" do resources :users # if anything else comes through the signup subdomain, the line below catches it route "/*glob", :to => "errors#404" end # these are not checked at all if the subdomain is 'signup' resources :cars resources :stations