How can I go about making my routes recognise an optional prefix parameter as follows:
/*lang/controller/id
In that the lang part is optional, and has a default value if it’s not specified in the URL:
/en/posts/1 => lang = en /fr/posts/1 => lang = fr /posts/1 => lang = en
EDIT
Ideally, I’m looking to do this across many controllers and actions by mapping a namespace:
map.namespace '*lang' do |lang| lang.resources :posts lang.resources :stories end
OK, I’ve managed to sort out this problem:
THere is no way of doing this in Rails by default (at least, not yet). Instead of using namespaces and default values, I needed to install Sven Fuchs’ routing filter.
Once the plugin is installed, I added the following file to my lib directory:
I added this line to routes.rb:
This basically fills out a before and after hook, generated by the plugin, that wraps the rails routing.
When a url is recognised, and before Rails gets to do anything with it, the around_recognize method is called. This will extract a two-letter code representing the locale, and pass it through in the params, defaulting to ‘en’ if no locale is specified.
Likewise, when a url is generated, the locale parameter will be pushed into the URL on the left side.
This gives me the following urls and mappings:
All existing url helpers work as before, with the only difference being that unless the locale is specified, it is preserved: