James Pierce
James Pierce

Reputation: 558

Rails Routing Conditional with multiple value options

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?

Upvotes: 1

Views: 646

Answers (1)

tadman
tadman

Reputation: 211600

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.

Upvotes: 2

Related Questions