Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Subdomain constraint and excluding certain subdomains

In my routes.rb file I want to use the subdomain constraints feature in rails3 however I would like to exclude certain domains from the catch all route. I dont want to have certain controller in a specific subdomain. What would be the best practice in doing so.

# 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
like image 571
George Drummond Avatar asked May 07 '11 20:05

George Drummond


3 Answers

You can use negative lookahead in your constraint regex to exclude some domains.

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

Try this out on Rubular

like image 128
edgerunner Avatar answered Oct 05 '22 22:10

edgerunner


this is the solution I came to.

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

it will match api but not apis

like image 43
George Drummond Avatar answered Oct 05 '22 22:10

George Drummond


Using a negative lookahead as suggested by edgerunner & George is great.

Basically the pattern is going to be:

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

This is the same as George's suggestion but I changed the \b to \Z — changing from a word boundary to the end of the input string 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
like image 42
Alan H. Avatar answered Oct 06 '22 00:10

Alan H.