Welcome to Working With Rails

 

Discussion Forums

Discuss all things Ruby on Rails with perhaps the web's most vibrant group of Ruby on Rails enthusiasts.
Catch invalid locale values in url
6 Posts
Catch invalid locale values in url

Hi,

Could someone tell me how I could catch invalid locale values in the url? I've added , :path_prefix => '/:locale' to my map.resources, so I could create a url like this domain.tld/locale/controller.

Thanks

You should use a before filter in your Application Controller that set a default local value is it are invalid.

I've added a the before_filter (http://pastie.org/508180)

But when I surf to domain.tld/nl ->but there is a route error (see pastie).

I'd like to surf to a url, just with a /language, than it should be forwarded to the sites controller. for example

domain.tld/nl -> sites controller domain.tld/fr -> sites controller domain.tld/other -> splash controller domain.tld/none -> splash controller

How could I do this?

Try to see this documentation http://api.rubyonrails.org/classes/ActionController/Resources.html

and find option ':requirements' where you can specify the regular expression for your param. For example :

map.connect ':lang/:controller/:action/:id', :controller => 'application', :action => 'index', :requirements => {:lang => /en|ar/}

You didn't include your route definitions in your pastie, but in your first post you wrote that you set up your routes to match this pattern:

/:locale/:controller

The examples you gave don't match this pattern, because they have a :locale component, but not a :controller component. So, without a matching route you get a routing error and your before_filter never comes into play. The locale component of your URL is simply a prefix, so you still need the rest of the URL. Try something like

/fr/sites

You'll also probably need to supply an action, although this example should default to #index.

Using the requirements option in the route definition will restrict your valid routes to those that match the specified regular expressions, but if they don't match you'll end up with routing errors again.

As for your before_filter, you probably want to only redirect if the locale is not valid. Once you're in a controller's before_filter you know the URL has matched a valid route; if the locale is appropriate then you allow the controller action to proceed normally. This way you can reuse the before_filter on other controllers that have the same locale requirements.

Thanks Adam, I've modified my route description and Robins. So I ended up with : map.connect ':locale/:controller', :controller => :sites

This works without any problem, I just have to adjust some settings involving the sessions and cookies.

Thanks everybody for helping

6 Posts
Login to add your message