In this second part of a four-part article series on adding support for multiple languages to a Ruby-on-Rails ecomerce application, you will learn how to use Globalize to add this important capability. This article is excerpted from chapter 10 of the book Practical Rails Projects, written by Eldon Alameda (Apress; ISBN: 1590597818).
Going Global with Multiple Language Support - Implementing the Change Locale User Story (Page 3 of 4 )
The base language, or default locale, for Emporium is US English. The user should be able to change to another language by clicking a link. For example, by accessing the following URL, the user can change the locale to British English:
Accessing the following URL changes the locale to Swedish:
Note that the link contains the locale parameter, which tells your system which locale the user wants to use. The code that changes the locale is easily implemented as a before_filter . As explained in Chapter 5, filters allow you to run code before, around, and after the controllerís action is called. In our case, the set_locale filter (Listing 10-1) is called before anything else is called.
Next, open app/controllers/application.rb in your editor and add the code for the set_locale method shown in Listing 10-1.
Listing 10-1. The set_locale Filter
class ApplicationController < ActionController::Base before_filter :set_locale
begin Locale.set locale session[:locale] = locale rescue Locale.set DEFAULT_LOCALE end end end
The filter looks for a user-specified locale from the request parameters. If the locale is not found in the request parameters, it looks for a locale stored in the session. If the locale is not found in either the request or session, it tries to use the HTTP_ACCEPT_LANGUAGE header, which is sent out by the browser. Note that the algorithm falls back on the default locale, which we defined in the environment.rb configuration file, if all other methods of discovering the userís locale fail.
Tip To set the HTTP_ACCEPT_LANGUAGE HTTP header in Firefox, select Tools ? Options and click the Advanced icon at the top of the Options dialog box. Then click the Edit Languages button on the General tab, as shown in Figure 10-2.
Lastly, the filter stores the locale in the session, so users donít need to change the locale every time they navigate to a new page. The filter falls back on the default locale if the user specifies an invalid locale.
Figure 10-2.Setting the preferred language with the HTTP_ACCEPT_LANGUAGE header