Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Exclude all other resources from subdomain in Rails

I have a Rails 4.0 app with that allows users to access blogs through subdomains. My routes currently look like this:

match '', to: 'blogs#show', via: [:get, :post], constraints: lambda { |r| r.subdomain.present? && r.subdomain != 'www' }

resources :foobars

Now, when I navigate to somesubdomain.example.com I am indeed taken to the showaction of the blogs controller action, as expected.

When I navigate to example.com/foobars I can access the index action of the foobars controller, as expected.

However, I only get a behavior I do not desire: When I navigate to somesubdomain.example.com/foobars, I can still access the the index action of foobars controller.

Is there a way to limit or exclude all resources that I do not specifically allow for a particular subdomain (i.e. somesubdomain.example.com/foobars will not work unless otherwise specified).

Thanks!

like image 447
Yuval Karmi Avatar asked Nov 01 '22 07:11

Yuval Karmi


1 Answers

If you need to define a specific subdomain to exclude from a set of routes you can simply do this (uses negative lookahead regex):

  # exclude all subdomains with 'www'
  constrain :subdomain => /^(?!www)(\w+)/ do
    root to: 'session#new' 
    resources :foobars
  end

Or similarly, to define a specific subdomain to include a set of routes you could do this:

  # only for subdomain matching 'somesubdomain'
  constrain :subdomain => /^somesubdomain/ do
    root to: 'blog#show' 
    resources :foobars
  end

Another approach would be to define the constraint match in a class (or module) and then wrap all routes within constraints block:

class WorldWideWebSubdomainConstraint
  def self.matches?(request)
    request.subdomain.present? && request.subdomain != 'www'
  end
end

App::Application.routes.draw do

  # All "www" requests handled here
  constraints(WorldWideWebSubdomainConstraint.new) do
    root to: 'session#new' 
    resources :foobars
  end

  # All non "www" requests handled here
  root to: 'blogs#show', via: [:get, :post]

end
like image 88
benjaminjosephw Avatar answered Nov 09 '22 08:11

benjaminjosephw