Chack
unread,Apr 2, 2011, 2:47:31 AM4/2/11Sign in to reply to author
Sign in to forward
You do not have permission to delete messages in this group
Either email addresses are anonymous for this group or you need the view member email addresses permission to view the original message
to I18n Routing
Hello again,
First thanks for the great gem. I've been playing around for a while
to figure out how to prefix urls with the locale. In generally this is
very easy to accomplish via scoping like this:
#routes.rb
Multilang::Application.routes.draw do
localized(I18n.available_locales, :verbose => true) do
scope "/:locale", :locale => /#{I18n.available_locales.join('|')}/
do
match "/asdf" => 'home#asdf', :as => :asdf
match "/abcd" => 'home#abcd', :as => :abcd
root :to => 'home#index'
end
end
end
However, this can lead to routing conflicts when a route can have
different meanings depending on your locale. Imagine some language xy
translating 'asdf' to 'word', and language yz translating 'abcd' to
'word' also. Now /xz/word will as well point to home#asdf since the
translation allows to use the locale across all language prefixes.
However I found a solution to this problem i want to share with you :)
It doesnt even require monkey patching anything. Since this gem sets
the i18n_locale constraint, we can just use that instead in our
routing.
localized(I18n.available_locales, :verbose => true) do
scope "/:i18n_locale", :constraints => {:i18n_locale => /
#{I18n.available_locales.join('|')}/} do
match "/asdf" => 'home#asdf', :as => :asdf
match "/abcd" => 'home#abcd', :as => :abcd
root :to => 'home#index'
end
end
Now, since i18n_routing internally set the constraint to the locale, /
xy/word and /yz/word can be used independently and no longer conflict.
Obviously you also have to make according changes in your
application_controller like this:
#application_controller.rb
before_filter :set_locale
def set_locale
I18n.locale = params[:i18n_locale]
end
def default_url_options(options={})
logger.debug "default_url_options is passed options:
#{options.inspect}\n"
{ :i18n_locale => I18n.locale }
end
Maybe this should be added to the wiki pages? :)