【问题标题】:Rails 3 Routing Constraint and RegexRails 3 路由约束和正则表达式
【发布时间】:2011-05-09 00:54:29
【问题描述】:

我希望匹配路径中的模式state/city,除非状态变量等于“auth”

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

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

我正在使用omniauth,它要求你去/auth/twitter进行身份验证,但是当我输入rake routes时找不到它。

【问题讨论】:

    标签: ruby-on-rails regex routing omniauth


    【解决方案1】:

    基于 mu is too short 的 cmets,这是我想出的答案:

    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
    

    【讨论】:

    • matches? 中使用!request.fullpath.start_with?('/auth/') 可能会更好,还不如保留整个/auth 命名空间。
    【解决方案2】:

    您应该能够在您的州/城市路线之前定义您的 /auth 路线:

    Route priority

    并非所有路线都是平等创建的。路由的优先级由 config/routes.rb 文件中路由的出现顺序定义。优先级从上到下。

    所以这个命令应该做正确的事:

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

    您可能希望通过将您的州/城市路线放入自己的命名空间来完全避免该问题:

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

    这为将来的其他用途留下了顶层。

    【讨论】:

    • 我不能把它们放在它们自己的命名空间中,因为这是一个虚 url。我也不确定优先级发生了什么,因为我使用的是在 Rack 中运行的 omniauth gem。事实上,我的match :state/:city 已经在路由文件的最后一行了。
    • 您可能需要更新您的问题,让人们知道您正在使用omniauth。我不知道omniauth在做什么。您是否尝试过使用constraints object 排除/auth
    • 不,我没有使用约束对象,希望内联正则表达式可以解决问题,但似乎没有。
    猜你喜欢
    • 1970-01-01
    • 2016-09-20
    • 2019-02-10
    • 2011-06-01
    • 1970-01-01
    • 2011-11-21
    • 2016-06-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多