【问题标题】:Subdomain constraint and excluding certain subdomains子域约束和排除某些子域
【发布时间】:2011-08-20 21:36:46
【问题描述】:

在我的routes.rb 文件中,我想使用 rails3 中的子域约束功能,但是我想从 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

【问题讨论】:

    标签: ruby-on-rails ruby regex ruby-on-rails-3


    【解决方案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
    

    【讨论】:

      【解决方案2】:

      按照 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
      

      【讨论】:

        【解决方案3】:

        这是我的解决方案。

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

        它将匹配 api apis

        【讨论】:

        • 它确实排除了api 而不是apis,但请记住,它也会排除api-foo。使用\Z(字符串结尾)而不是\b(字边界,乔治清楚地知道)将不再排除api-foo。 (当然,这完全取决于您为什么要排除这些字符串,但我认为更多选项会更好!)
        【解决方案4】:

        您可以在约束正则表达式中使用negative lookahead 来排除某些域。

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

        Rubular试试这个

        【讨论】:

        • 感谢您帮助我使用这项技术。我自己对其进行了修改,以进一步限制正则表达式不匹配具有第一位和其他字符的模式。
        • @edgerunner 也感谢 Rubular 链接!
        猜你喜欢
        • 2014-11-05
        • 1970-01-01
        • 2010-12-16
        • 1970-01-01
        • 2014-12-10
        • 1970-01-01
        • 1970-01-01
        • 2017-08-05
        • 1970-01-01
        相关资源
        最近更新 更多