Switching locale

How about switching the locale?

Getting locale option from params.

In the application_controller.rb file:

 1  class ApplicationController < ActionController::Base
 2    protect_from_forgery
 4    before_filter :set_locale
 6    def set_locale
 7      I18n.locale = params[:locale] || I18n.default_locale
 8    end
 9  end


1def set_locale
2  if params[:locale].in? %W(en zh-TW)
3    I18n.locale = params[:locale]
4  end

And now, we can access different with the params query:

Automatically appending the locale params to URL.

Rails comes with a default_url_options that is the default query string and values that will be attached in the URL.

We can override the default_url_options. Add the following method in the application_controller.rb file.

1def default_url_options
2  { locale: I18n.locale }

This only applies to URL which is generated by rails, such as root_path. Manually typing the URL will not get the default_url_options attached.

And than the UI to switch. Since we want the language available everywhere, put it in the applicotian.html.erb file.

1<a href='?locale=zh-TW'></a> | <a href='?locale=en'>EN</a>

For more detail, check http://guides.rubyonrails.org/i18n.html. For example, adding locale as part of the URL

What’s next? We’re going to take a look at “Pow local server”.

overlaied image when clicked on thumbnail

Makzan | Ruby on rails 101 | Table of Content