2011-05-09 77 views
1

我期待的模式state/city路徑匹配,除非狀態變量等於「權威性」Rails 3的路由約束和正則表達式

match '/:state/:city' => 'cities#index', :as => :state_cities, :constraints => {:state => /(?!auth)/ } 

例如,mydomain.com/fl/miami好。 mydomain.com/auth/twitter不好。

我使用的是omniauth,它需要您去/auth/twitter進行身份驗證,但是當我輸入rake routes時無處可查。

回答

6

基於畝太短的評論,這裏就是答案我已經出來:

match '/:state/:city' => 'cities#index', :as => :state_cities, :constraints => OmniauthPassThru.new 

的lib/omniauth_pass_thru.rb

class OmniauthPassThru 
    def initialize 
     @passthru = ["/auth/facebook", "/auth/twitter"] 
    end 

    def matches?(request) 
     return false if @passthru.include?(request.fullpath) 
     true 
    end 
end 
+3

在'matches?'中使用'!request.fullpath.start_with?('/ auth /')'可能會更好一些,不妨保留整個'/ auth'命名空間。 – 2011-05-09 02:15:31

4

你應該能夠你的國家/城市路線之前定義/auth路線:

Route priority

並非所有的路線都是一樣的。根據config/routes.rb文件中路由的出現順序,路由具有優先級。優先順序從上到下。

所以這個順序應該做正確的事情:

match '/auth/twitter' => ... 
match '/:state/:city' => ... 

您可能想要把你的國家/城市幹道自己的命名空間來完全避免問題:

match '/place/:state/:city' => ... 

那將其最高級別清除以供將來使用。

+0

我不能把他們在自己的名稱空間,因爲這是一個虛榮網址。由於我使用的是運行在Rack中的omniauth gem,因此我也不確定發生了什麼。實際上,我的'match:state /:city'已經在路由文件的最後一行。 – Dex 2011-05-09 01:20:39

+1

你可能想更新你的問題,讓別人知道你正在使用omniauth。我不知道omniauth在做什麼。您是否嘗試過使用[constraints對象](http://edgeguides.rubyonrails.org/routing.html#advanced-constraints)來排除'/ auth'? – 2011-05-09 01:47:30

+0

不,我沒有使用約束對象,希望內聯正則表達式能夠做到這一點,但似乎並不是這樣。 – Dex 2011-05-09 01:51:07