views:

13

answers:

1

I have a rails route that is based on two conditions, that the domain and subdomain are a specific value. The problem is that there are multiple possible values for subdomain to work, but I can't seem to be able to pass them as an array or hash.

map.with_options(:conditions => {:domain => AppConfig['base_domain'], :subdomain => 'www'..'www3'}) do |signup|
    signup.plans '/signup', :controller => 'accounts', :action => 'plans'
    ...[truncated]...
end

The above example works as accepting www, www1, www2 & www3 as a value for the subdomain. However, that doesn't really solve my needs. I need to be able to accept a value of '' (nothing), 'www' and 'www2' so I tried something to the extend of:

map.with_options(:conditions => {:domain => AppConfig['base_domain'], :subdomain => ['','www','www2']}) do |signup|

That's similar to how you would set it up in ActiveRecord but it doesn't seem to be the same for routes.

Does anybody know now I can specify three values that aren't sequential?

A: 

If you can render it as a regular expression, you can use it as a condition. Converting an array to a regular expression is quite easy:

:subdomain => Regexp.new(%w[ www www3 ].collect { |p| Regexp.escape(p) }.join('|'))

Since you're just dealing with a simple pattern anyway, why not express it as this?

:subdomain => /www\d*/

It is important to note that the regular expressions used by routes are not supposed to be anchored using ^ or $ like you usually would. They must match completely to be valid, and partial matches are ignored.

tadman
I'm not too familiar with regular expressions, but that I know enough that works great for www#, but in addition to www and www2, I also need it to respond to '' (no subdomain). In other words, I need domain.com/signup, www.domain.com/signup, and www2.domain.com/signup to work. I'm having trouble with matching it without a subdomain.
James Pierce
Regular expressions are such a powerful tool it's worth the time to read more about them. There's easier ways to test if your expression is working or not than using `irb`, although that can be good, like http://rubular.com/ What I'm wondering now is if you can't HTTP redirect www? to a canonical domain.com to avoid all these matches. A better regular expression would be: `/www\d*|/` to match on nothing as well.
tadman