The fact that there are so many different countries, people and languages makes it very interesting to watch all them to use a single tool. Besides the different cultures of programming, there is a definite difference in languages that the tool needs to support in order to become widely used.
Luckily, if the tool is written to support UTF-8 encoding it is guaranteed to support all the modern spoken languages. Since UTF-8 is able to represent any character in the Unicode standard, yet the initial encoding of byte codes and character assignments for UTF-8 is backwards compatible with ASCII, and for these reasons, it is steadily becoming the preferred encoding for e-mail, web pages, and other places where characters are stored or streamed – in our case it is a mySql database.
When working with Rails on mySql, it is most of the time, a good practice to make sure the UTF-8 support is enabled, since even if there is no immediate need, in the future, clients of the Rails application could come from different points of Earth – due to the Earthy nature of the Internet.
Here are 3 simple steps on how to configure a Rails application and mySql database to support UTF-8 encoding:
Step 1. From the Rails side, due to the “convention over configuration” principle, there is only one thing to make sure of. Open the Rails database configuration file:
vi config/database.yml |
(here I used “vi” text editor, but any editor of choice can be used: notepad/textmate/emacs/aptana.. etc)
Notice the “encoding” option, and make sure it is set to “utf-8”:
... development: adapter: mysql >>> encoding: utf8 database: my_international_db username: user password: password socket: /var/run/mysqld/mysqld.sock ... |
That will conclude this step, since everything from Rails side is configured. Simple? Well, yes – Rails is well designed to keep it simple stupid.
Above is the sample for the Rails development environment, make sure that testing and production environments have the same configuration.
Step 2. Now it is time to configure MySql server. This will be done by editing “my.cnf” – mySQL configuration file:
vi /etc/mysql/my.cnf |
There are several sections in the file. Modify two of them – “client” and “mysqld” as shown below to configure mySql for UTF-8 support:
... [client] default-character-set=utf8 ... [mysqld] default-character-set=utf8 character-set-server=utf8 default-collation=utf8_unicode_ci ... |
Step 3. The very last action would be to restart MySql server. Here is an example on how to do it in Linux (Ubuntu):
sudo /etc/init.d/mysql restart |
NOTE: Only databases that are created after the above change will support UTF-8 encoding.
After these three steps Rails application and MySql server are configured, and ready to serve the whole planet!