1

I've written an application that uses a subdomain per user account to segregate environments. All this is working fine, except I have one issue. I can't get both www and "" to have a different root path than all other subdomains.

For all account subdomains, I have a root page of:

root :to => "applications#index"

I need this to be the root page for all subdomains except for a blank subdomain of "" and then "www". For www, I have this in the routes:

constraints(:subdomain => "www") do
    root :to => "promos#index"
  end

What I'm struggling with, is getting it so "" will also use promos#index as the root path. When it's not the root path, mywebsite.com sends them to the applications#index, which requires a login. Something I don't want users to see on a first visit.

Is there anyway to modify this code to also include mywebsite.com to have the different root? I've tried things like duplicating the code with "", but this tends to mess up all other subdomains, regardless of order. Below is the in of my routes file:

constraints(:subdomain => "www") do
    root :to => "promos#index"
  end  

  root :to => "applications#index"

1 Answer 1

3

You can use an object that implements 'matches?' to do some real custom stuff. Below we'll set applications#index if you are a customer subdomain, and send you to promo#index if you're not

In your routes:

Yourapp::Application.routes.draw do
  constraints(SubDomain) do
    root :to => "applications#index"
  end
  root :to => "promo#index"
  ...
end

and then the Subdomain matcher file:

config/initializers/subdomain.rb

class SubDomain
  def self.matches?(request)
    case request.subdomain
    when 'www', '', nil, #admin/api/etc could also go here
      false
    else
      true
    end
  end
end

subdomain.rb can also live in lib (if it's being auto-loaded)

1
  • 1
    That was amazingly elegant and worked like an absolute charm. If I could hug and kiss you I would :P - Seriously though, thank you so much.
    – Kombo
    Jun 3, 2011 at 17:54

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.