2011-05-07 53 views
6

在我的routes.rb文件中,我想使用rails3中的子域約束功能,但是我想從捕獲所有路由中排除某些域。我不想在特定子域中擁有某個控制器。這樣做最好的做法是什麼?子域約束和排除某些子域

# 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 

回答

11

您可以在約束正規表達式中使用negative lookahead來排除某些域。

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

嘗試了這一點上Rubular

+1

謝謝你幫助我使用這種技術。我自己修改它以進一步限制正則表達式與之後的第一位和附加字符不匹配。 – 2011-05-08 11:13:09

+1

@edgerunner感謝您的Rubular鏈接! – scarver2 2013-07-18 19:14:16

3

這是我來解決。

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

它將匹配apiapis

+0

它確實排除'api'而不是'apis',但請記住它也會排除'api-foo'。使用'\ Z'(字符串結尾)而不是'\ b'(字面邊界,正如George清楚地知道的)將不再排除'api-foo'。 (當然,這一切都取決於你爲什麼要排除這些字符串,但更多的選擇更好,我想!) – 2011-07-15 20:40:06

1

使用負先行通過edgerunner &的建議喬治是偉大的。

基本格局將是:

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

這是同喬治的建議,但我改變了\b\Z - 從文字邊界的輸入字符串本身的結尾變化(如備註在我對喬治的回答的評論中)。

這裏有一堆的測試案例示出差異:,我只是想到了另外一個辦法,可能取決於你想要什麼工作

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 
1

重溫這個老問題...

Rails的路由器嘗試按照指定的順序將請求匹配到路由。如果發現匹配,則其餘路線是而不是檢查。在您保留的子域塊中,您可以將glob up all remaining routes發送到錯誤頁面。

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