Subdomain restriction and exclusion of specific subdomains

In my routes.rb I want to use the subdomain restriction function in rails3, however I would like to exclude certain domains from the catch all route. I do not want to have a specific controller in a specific subdomain. What would be best in this.

 # 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 
+6
source share
4 answers

You can use negative browsing in your regex constraint to exclude certain domains.

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

Try it on Rubular

+11
source

This is the decision I have come to.

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

it will match api but not apis

+3
source

The use of the negative gaze proposed by edgerunner and George is great.

In principle, the template will be:

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

This is the same as George’s sentence, but I changed \b to \Z - changing from the word boundary to the end of the input line itself (as noted in my comment on George’s answer).

Here are a bunch of test cases showing the difference:

 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
source

Repeating this old question, I just thought of a different approach that might work depending on what you want ...

The Rails Router attempts to match the request with the route in the specified order. If a match is found, the remaining routes are not marked. In the reserved subdomain block, you can combine all the remaining routes and send a request to the error page.

 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 
+1
source

Source: https://habr.com/ru/post/887530/


All Articles