aboutsummaryrefslogtreecommitdiffstats
path: root/railties/doc/guides/source/i18n.txt
blob: 2638807761dd984778eedb1e1fcdbd8e77818225 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
The Rails Internationalization (I18n) API
=========================================

The Ruby I18n (shorthand for _internationalization_) gem which is shipped with Ruby on Rails (starting from Rails 2.2) provides an easy-to-use and extensible framework for translating your application to a single custom language other than English or providing multi-language support in your application.

NOTE: The Ruby I18n framework provides you with all neccessary means for internationalization/localization of your Rails application. You may, however, use any of various plugins and extensions available. See Rails http://rails-i18n.org/wiki[I18n Wiki] for more information.

== How I18n in Ruby on Rails works

Internationalization is a complex problem. Natural languages differ in so many ways (eg. in pluralization rules) that it is hard to provide tools for solving all problems at once. For that reason the Rails I18n API focuses on:

* providing support for English and similar languages out of the box
* making it easy to customize and extend everything for other languages

As part of this solution, *every static string in the Rails framework* -- eg. Active Record validation messages, time and date formats -- *has been internationalized*, so _localization_ of a Rails application means "over-riding" these defaults.

=== The overall architecture of the library

Thus, the Ruby I18n gem is split into two parts:

* The public API of the i18n framework -- a Ruby module with public methods and definitions how the library works
* A default backend (which is intentionally named _Simple_ backend) that implements these methods

As a user you should always only access the public methods on the I18n module, but it is useful to know about the capabilities of the backend.

NOTE: It is possible (or even desirable) to swap the shipped Simple backend with a more powerful one, which would store translation data in a relational database, GetText dictionary, or similar. See section <<_using_different_backends,Using different backends>> below.

=== The public I18n API

The most important methods of the I18n API are:

[source, ruby]
-------------------------------------------------------
translate         # Lookup text translations
localize          # Localize Date and Time objects to local formats
-------------------------------------------------------

These have the aliases #t and #l so you can use them like this:

[source, ruby]
-------------------------------------------------------
I18n.t 'store.title'
I18n.l Time.now
-------------------------------------------------------

There are also attribute readers and writers for the following attributes:

[source, ruby]
-------------------------------------------------------
load_path         # Announce your custom translation files
locale            # Get and set the current locale
default_locale    # Get and set the default locale
exception_handler # Use a different exception_handler
backend           # Use a different backend
-------------------------------------------------------

So, let's internationalize a simple Rails application from the ground up in the next chapters!

== Setup the Rails application for internationalization

There are just a few, simple steps to get up and running with I18n support for your application.

=== Configure the I18n module

Following the _convention over configuration_ philosophy, Rails will set-up your application with reasonable defaults. If you need different settings, you can overwrite them easily.

Rails adds all +.rb+ and +.yml+ files from +config/locales+ directory to your *translations load path*, automatically.

See the default +en.yml+ locale in this directory, containing a sample pair of translation strings:

[source, ruby]
-------------------------------------------------------
en:
  hello: "Hello world"
-------------------------------------------------------

This means, that in the +:en+ locale, the key _hello_ will map to _Hello world_ string. Every string inside Rails is internationalized in this way, see for instance Active Record validation messages in the http://github.com/rails/rails/blob/master/activerecord/lib/active_record/locale/en.yml[+activerecord/lib/active_record/locale/en.yml+] file or time and date formats in the http://github.com/rails/rails/blob/master/activesupport/lib/active_support/locale/en.yml[+activesupport/lib/active_support/locale/en.yml+] file. You can use YAML or standard Ruby Hashes to store translations in the default (Simple) backend.

The I18n library will use *English* as a *default locale*, ie. if you don't set a different locale, +:en+ will be used for looking up translations.

The *translations load path* (+I18n.load_path+) is just a Ruby Array of paths to your translation files that will be loaded automatically and available in your application. You can pick whatever directory and translation file naming scheme makes sense for you. 

NOTE: The backend will lazy-load these translations when a translation is looked up for the first time. This makes it possible to just swap the backend with something else even after translations have already been announced.

The default +environment.rb+ files has instruction how to add locales from another directory and how to set different default locale. Just uncomment and edit the specific lines.

[source, ruby]
-------------------------------------------------------
# The internationalization framework can be changed
# to have another default locale (standard is :en) or more load paths.
# All files from config/locales/*.rb,yml are added automatically.
# config.i18n.load_path << Dir[File.join(RAILS_ROOT, 'my', 'locales', '*.{rb,yml}')]
# config.i18n.default_locale = :de
-------------------------------------------------------

=== Optional: custom I18n configuration setup

For the sake of completeness, let's mention that if you do not want to use the +environment.rb+ file for some reason, you can always wire up things manually, too.

To tell the I18n library where it can find your custom translation files you can specify the load path anywhere in your application - just make sure it gets run before any translations are actually looked up. You might also want to change the default locale. The simplest thing possible is to put the following into an *initializer*:

[source, ruby]
-------------------------------------------------------
# in config/initializer/locale.rb

# tell the I18n library where to find your translations
I18n.load_path << Dir[ File.join(RAILS_ROOT, 'lib', 'locale', '*.{rb,yml}') ]

# set default locale to something else then :en
I18n.default_locale = :pt
-------------------------------------------------------

=== Setting and passing the locale

If you want to translate your Rails application to a *single language other than English* (the default locale), you can set I18n.default_locale to your locale in +environment.rb+ or an initializer as shown above, and it will persist through the requests.

However, you would probably like to *provide support for more locales* in your application. In such case, you need to set and pass the locale between requests.

WARNING: You may be tempted to store choosed locale in a _session_ or a _cookie_. *Do not do so*. The locale should be transparent and a part of the URL. This way you don't break people's basic assumptions about the web itself: if you send a URL of some page to a friend, she should see the same page, same content. A fancy word for this would be that you're being http://en.wikipedia.org/wiki/Representational_State_Transfer[_RESTful_]. There may be some exceptions to this rule, which are discussed below.

The _setting part_ is easy. You can set locale in a +before_filter+ in the ApplicationController like this:

[source, ruby]
-------------------------------------------------------
before_filter :set_locale
def set_locale
  # if params[:locale] is nil then I18n.default_locale will be used
  I18n.locale = params[:locale] 
end
-------------------------------------------------------

This requires you to pass the locale as a URL query parameter as in +http://example.com/books?locale=pt+. (This is eg. Google's approach). So +http://localhost:3000?locale=pt+ will load the Portugese localization, whereas +http://localhost:3000?locale=de+ would load the German localization, and so on.

Of course, you probably don't want to manually include locale in every URL all over your application, or want the URLs look differently, eg. the usual +http://example.com/pt/books+ versus +http://example.com/en/books+. Let's discuss the different options you have.

IMPORTANT: Following examples rely on having locales loaded into your application available as an array of strings like +["en", "es", "gr"]+. This is not inclued in current version of Rails 2.2 -- forthcoming Rails version 2.3 will contain easy accesor +available_locales+. (See http://github.com/svenfuchs/i18n/commit/411f8fe7[this commit] and background at http://rails-i18n.org/wiki/pages/i18n-available_locales[Rails I18n Wiki].) 

We have to include support for getting available locales manually in an initializer like this:

[source, ruby]
-------------------------------------------------------
# config/initializers/available_locales.rb
#
# Get loaded locales conveniently
# See http://rails-i18n.org/wiki/pages/i18n-available_locales
module I18n
  class << self
    def available_locales; backend.available_locales; end
  end
  module Backend
    class Simple
      def available_locales; translations.keys.collect { |l| l.to_s }.sort; end
    end
  end
end

# You need to "force-initialize" loaded locales
I18n.backend.send(:init_translations)

AVAILABLE_LOCALES = I18n.backend.available_locales
RAILS_DEFAULT_LOGGER.debug "* Loaded locales: #{AVAILABLE_LOCALES.inspect}"
-------------------------------------------------------

You can then wrap the constant for easy access in ApplicationController:

[source, ruby]
-------------------------------------------------------
class ApplicationController < ActionController::Base
  def available_locales; AVAILABLE_LOCALES; end
end
-------------------------------------------------------

=== Setting locale from the domain name

One option you have is to set the locale from the domain name, where your application runs. For example, we want +www.example.com+ to load English (or default) locale, and +www.example.es+ to load Spanish locale. Thus the _top-level domain name_ is used for locale setting. This has several advantages:

* Locale is an _obvious_ part of the URL
* People intuitively grasp in which language the content will be displayed
* It is very trivial to implement in Rails
* Search engines seem to like that content in different languages lives at different, inter-linked domains

You can implement it like this in your ApplicationController:

[source, ruby]
-------------------------------------------------------
before_filter :set_locale
def set_locale
  I18n.locale = extract_locale_from_uri
end
# Get locale from top-level domain or return nil if such locale is not available
# You have to put something like:
#   127.0.0.1 application.com
#   127.0.0.1 application.it
#   127.0.0.1 application.pl
# in your /etc/hosts file to try this out locally
def extract_locale_from_tld
  parsed_locale = request.host.split('.').last
  (available_locales.include? parsed_locale) ? parsed_locale  : nil
end
-------------------------------------------------------

We can also set the locale from the _subdomain_ in very similar way:

[source, ruby]
-------------------------------------------------------
# Get locale code from request subdomain (like http://it.application.local:3000)
# You have to put something like:
#   127.0.0.1 gr.application.local
# in your /etc/hosts file to try this out locally
def extract_locale_from_subdomain
  parsed_locale = request.subdomains.first
  (available_locales.include? parsed_locale) ? parsed_locale  : nil
end
-------------------------------------------------------

=== Setting locale from the URL params

* TODO : Based on *+default_url options+*, http://github.com/karmi/test_default_url_options/blob/master/app/controllers/application.rb#L22-26

* TODO : Discussion of plugins (translate_routes and routing_filter)


TIP: For setting locale from URL see http://rails-i18n.org/wiki/pages/how-to-encode-the-current-locale-in-the-url[How to encode the current locale in the URL] in the Rails i18n Wiki.

Now you've initialized I18n support for your application and told it which locale should be used. With that in place you're now ready for the really interesting stuff.

== Internationalize your application

The process of "internationalization" usually means to abstract all strings and other locale specific bits out of your application. The process of "localization" means to then provide translations and localized formats for these bits. <<1>>

So, let's internationalize something. You most probably have something like this in one of your applications:

[source, ruby]
-------------------------------------------------------
# config/routes.rb
ActionController::Routing::Routes.draw do |map|
  map.root :controller => 'home', :action => 'index'
end
  
# app/controllers/home_controller.rb
class HomeController < ApplicationController
  def index
    flash[:notice] = "Hello flash!"
  end
end

# app/views/home/index.html.erb
<h1>Hello world!</h1>
<p><%= flash[:notice] %></p>
-------------------------------------------------------

image:images/i18n/demo_untranslated.png[rails i18n demo untranslated]

=== Adding Translations

Obviously there are two strings that are localized to English. In order to internationalize this code replace these strings with calls to Rails' #t helper with a key that makes sense for the translation:

[source, ruby]
-------------------------------------------------------
# app/controllers/home_controller.rb
class HomeController < ApplicationController
  def index
    flash[:notice] = t(:hello_flash)
  end
end

# app/views/home/index.html.erb
<h1><%=t :hello_world %></h1>
<p><%= flash[:notice] %></p>
-------------------------------------------------------

When you now render this view it will show an error message that tells you that the translations for the keys :hello_world and :hello_flash are missing.

image:images/i18n/demo_translation_missing.png[rails i18n demo translation missing]

NOTE: Rails adds a +t+ (+translate+) helper method to your views so that you do not need to spell out +I18n.t+ all the time. Additionally this helper will catch missing translations and wrap the resulting error message into a &lt;span class="translation_missing"&gt;.

So let's add the missing translations (i.e. do the "localization" part):

[source, ruby]
-------------------------------------------------------
# config/locale/en.yml
en:
  hello_world: Hello World
  hello_flash: Hello Flash
  
# config/locale/pirate.yml
pirate:
  hello_world: Ahoy World
  hello_flash: Ahoy Flash
-------------------------------------------------------  

There you go. Because you haven't changed the default_locale I18n will use English. Your application now shows:

image:images/i18n/demo_translated_en.png[rails i18n demo translated to english]

And when you change the URL to pass the pirate locale you get:

image:images/i18n/demo_translated_pirate.png[rails i18n demo translated to pirate]

NOTE You need to restart the server when you add new locale files.

=== Adding Date/Time formats

Ok, let's add a timestamp to the view so we can demo the date/time localization feature as well. To localize the time format you pass the Time object to I18n.l or (preferably) use Rails' #l helper. You can pick a format by passing the :format option, by default the :default format is used.

[source, ruby]
-------------------------------------------------------
# app/views/home/index.html.erb
<h1><%=t :hello_world %></h1>
<p><%= flash[:notice] %></p
<p><%= l Time.now, :format => :short %></p>
-------------------------------------------------------

And in our pirate translations file let's add a time format (it's already there in Rails' defaults for English):

[source, ruby]
-------------------------------------------------------
# config/locale/pirate.yml
pirate:
  time:
    formats:
      short: "arrrround %H'ish"
-------------------------------------------------------

So that would give you:

image:images/i18n/demo_localized_pirate.png[rails i18n demo localized time to pirate]

NOTE Right now you might need to add some more date/time formats in order to make the I18n backend work as expected. See the http://github.com/svenfuchs/rails-i18n/tree/master/rails/locale[rails-i18n repository] for starting points.


== Overview of the I18n API features

The following purposes are covered:

* lookup translations
* interpolate data into translations
* pluralize translations
* localize dates, numbers, currency etc.

=== Looking up translations

==== Basic lookup, scopes and nested keys

Translations are looked up by keys which can be both Symbols or Strings, so these calls are equivalent:

[source, ruby]
-------------------------------------------------------
I18n.t :message
I18n.t 'message'
-------------------------------------------------------

translate also takes a :scope option which can contain one or many additional keys that will be used to specify a “namespace” or scope for a translation key:

[source, ruby]
-------------------------------------------------------
I18n.t :invalid, :scope => [:active_record, :error_messages]
-------------------------------------------------------

This looks up the :invalid message in the Active Record error messages.

Additionally, both the key and scopes can be specified as dot separated keys as in:

[source, ruby]
-------------------------------------------------------
I18n.translate :"active_record.error_messages.invalid"
-------------------------------------------------------

Thus the following calls are equivalent:

[source, ruby]
-------------------------------------------------------
I18n.t 'active_record.error_messages.invalid'
I18n.t 'error_messages.invalid', :scope => :active_record
I18n.t :invalid, :scope => 'active_record.error_messages'
I18n.t :invalid, :scope => [:active_record, :error_messages]
-------------------------------------------------------

==== Defaults

When a default option is given its value will be returned if the translation is missing:

[source, ruby]
-------------------------------------------------------
I18n.t :missing, :default => 'Not here'
# => 'Not here'
-------------------------------------------------------

If the default value is a Symbol it will be used as a key and translated. One can provide multiple values as default. The first one that results in a value will be returned.

E.g. the following first tries to translate the key :missing and then the key :also_missing. As both do not yield a result the string "Not here" will be returned:

[source, ruby]
-------------------------------------------------------
I18n.t :missing, :default => [:also_missing, 'Not here']
# => 'Not here'
-------------------------------------------------------

==== Bulk and namespace lookup

To lookup multiple translations at once an array of keys can be passed:

[source, ruby]
-------------------------------------------------------
I18n.t [:odd, :even], :scope => 'active_record.error_messages'
# => ["must be odd", "must be even"]
-------------------------------------------------------

Also, a key can translate to a (potentially nested) hash as grouped translations. E.g. one can receive all Active Record error messages as a Hash with:

[source, ruby]
-------------------------------------------------------
I18n.t 'active_record.error_messages'
# => { :inclusion => "is not included in the list", :exclusion => ... }
-------------------------------------------------------

=== Interpolation

In many cases you want to abstract your translations so that variables can be interpolated into the translation. For this reason the I18n API provides an interpolation feature.

All options besides :default and :scope that are passed to #translate will be interpolated to the translation:

[source, ruby]
-------------------------------------------------------
I18n.backend.store_translations :en, :thanks => 'Thanks {{name}}!'
I18n.translate :thanks, :name => 'Jeremy'
# => 'Thanks Jeremy!'
-------------------------------------------------------

If a translation uses :default or :scope as a interpolation variable an I18n::ReservedInterpolationKey exception is raised. If a translation expects an interpolation variable but it has not been passed to #translate an I18n::MissingInterpolationArgument exception is raised.


=== Pluralization

In English there's only a singular and a plural form for a given string, e.g. "1 message" and "2 messages". Other languages (http://www.unicode.org/cldr/data/charts/supplemental/language_plural_rules.html#ar[Arabic], http://www.unicode.org/cldr/data/charts/supplemental/language_plural_rules.html#ja[Japanese], http://www.unicode.org/cldr/data/charts/supplemental/language_plural_rules.html#ru[Russian] and many more) have different grammars that have additional or less http://www.unicode.org/cldr/data/charts/supplemental/language_plural_rules.html[plural forms]. Thus, the I18n API provides a flexible pluralization feature.

The :count interpolation variable has a special role in that it both is interpolated to the translation and used to pick a pluralization from the translations according to the pluralization rules defined by CLDR:

[source, ruby]
-------------------------------------------------------
I18n.backend.store_translations :en, :inbox => {
  :one => '1 message', 
  :other => '{{count}} messages'
}
I18n.translate :inbox, :count => 2
# => '2 messages'
-------------------------------------------------------

The algorithm for pluralizations in :en is as simple as:

[source, ruby]
-------------------------------------------------------
entry[count == 1 ? 0 : 1]  
-------------------------------------------------------

I.e. the translation denoted as :one is regarded as singular, the other is used as plural (including the count being zero).

If the lookup for the key does not return an Hash suitable for pluralization an I18n::InvalidPluralizationData exception is raised.

=== Setting and passing a locale

The locale can be either set pseudo-globally to I18n.locale (which uses Thread.current like, e.g., Time.zone) or can be passed as an option to #translate and #localize.

If no locale is passed I18n.locale is used:

[source, ruby]
-------------------------------------------------------
I18n.locale = :de
I18n.t :foo 
I18n.l Time.now
-------------------------------------------------------

Explicitely passing a locale:

[source, ruby]
-------------------------------------------------------
I18n.t :foo, :locale => :de
I18n.l Time.now, :locale => :de
-------------------------------------------------------

I18n.locale defaults to I18n.default_locale which defaults to :en. The default locale can be set like this:

[source, ruby]
-------------------------------------------------------
I18n.default_locale = :de
-------------------------------------------------------

== How to store your custom translations

The shipped Simple backend allows you to store translations in both plain Ruby and YAML format. <<2>>

For example a Ruby Hash providing translations can look like this:

[source, ruby]
-------------------------------------------------------
{
  :pt => {
    :foo => {
      :bar => "baz"
    }
  }
}
-------------------------------------------------------

The equivalent YAML file would look like this:

[source, ruby]
-------------------------------------------------------
pt:
  foo:
    bar: baz
-------------------------------------------------------    

As you see in both cases the toplevel key is the locale. :foo is a namespace key and :bar is the key for the translation "baz".

Here is a "real" example from the ActiveSupport en.yml translations YAML file:

[source, ruby]
-------------------------------------------------------
en:
  date:
    formats:
      default: "%Y-%m-%d"
      short: "%b %d"
      long: "%B %d, %Y"
-------------------------------------------------------

So, all of the following equivalent lookups will return the :short date format "%B %d":

[source, ruby]
-------------------------------------------------------
I18n.t 'date.formats.short'
I18n.t 'formats.short', :scope => :date
I18n.t :short, :scope => 'date.formats'
I18n.t :short, :scope => [:date, :formats]
-------------------------------------------------------

Generally we recommend using YAML as a format for storing translations. There are cases though where you want to store Ruby lambdas as part of your locale data, e.g. for special date 

=== Translations for Active Record models

You can use the methods Model.human_name and Model.human_attribute_name(attribute) to transparently lookup translations for your model and attribute names.

For example when you add the following translations:

[source, ruby]
-------------------------------------------------------
en:
  activerecord:
    models:
      user: Dude
    attributes:
      user:
        login: "Handle"
      # will translate User attribute "login" as "Handle"
-------------------------------------------------------
      
Then User.human_name will return "Dude" and User.human_attribute_name(:login) will return "Handle".
      
==== Error message scopes

Active Record validation error messages can also be translated easily. Active Record gives you a couple of namespaces where you can place your message translations in order to provide different messages and translation for certain models, attributes and/or validations. It also transparently takes single table inheritance into account.

This gives you quite powerful means to flexibly adjust your messages to your application's needs.

Consider a User model with a validates_presence_of validation for the name attribute like this:

[source, ruby]
-------------------------------------------------------
class User < ActiveRecord::Base
  validates_presence_of :name
end
-------------------------------------------------------

The key for the error message in this case is :blank. Active Record will lookup this key in the namespaces:

[source, ruby]
-------------------------------------------------------
activerecord.errors.messages.models.[model_name].attributes.[attribute_name]
activerecord.errors.messages.models.[model_name]
activerecord.errors.messages
-------------------------------------------------------

Thus, in our example it will try the following keys in this order and return the first result:

[source, ruby]
-------------------------------------------------------
activerecord.errors.messages.models.user.attributes.name.blank
activerecord.errors.messages.models.user.blank
activerecord.errors.messages.blank
-------------------------------------------------------

When your models are additionally using inheritance then the messages are looked up for the inherited model class names are looked up. 

For example, you might have an Admin model inheriting from User:

[source, ruby]
-------------------------------------------------------
class Admin < User
  validates_presence_of :name
end
-------------------------------------------------------

Then Active Record will look for messages in this order:

[source, ruby]
-------------------------------------------------------
activerecord.errors.models.admin.attributes.title.blank
activerecord.errors.models.admin.blank
activerecord.errors.models.user.attributes.title.blank
activerecord.errors.models.user.blank
activerecord.errors.messages.blank
-------------------------------------------------------

This way you can provide special translations for various error messages at different points in your models inheritance chain and in the attributes, models or default scopes.

==== Error message interpolation

The translated model name, translated attribute name, and value are always available for interpolation.

So, for example, instead of the default error message "can not be blank" you could use the attribute name like this: "Please fill in your {{attribute}}".

count, where available, can be used for pluralization if present:

|=====================================================================================================
| validation                   | with option               | message                   | interpolation
| validates_confirmation_of    | -                         | :confirmation             | -
| validates_acceptance_of      | -                         | :accepted                 | -
| validates_presence_of        | -                         | :blank                    | -
| validates_length_of          | :within, :in              | :too_short                | count
| validates_length_of          | :within, :in              | :too_long                 | count
| validates_length_of          | :is                       | :wrong_length             | count
| validates_length_of          | :minimum                  | :too_short                | count
| validates_length_of          | :maximum                  | :too_long                 | count
| validates_uniqueness_of      | -                         | :taken                    | -
| validates_format_of          | -                         | :invalid                  | -
| validates_inclusion_of       | -                         | :inclusion                | -
| validates_exclusion_of       | -                         | :exclusion                | -
| validates_associated         | -                         | :invalid                  | -
| validates_numericality_of    | -                         | :not_a_number             | -
| validates_numericality_of    | :greater_than             | :greater_than             | count
| validates_numericality_of    | :greater_than_or_equal_to | :greater_than_or_equal_to | count
| validates_numericality_of    | :equal_to                 | :equal_to                 | count
| validates_numericality_of    | :less_than                | :less_than                | count
| validates_numericality_of    | :less_than_or_equal_to    | :less_than_or_equal_to    | count
| validates_numericality_of    | :odd                      | :odd                      | -
| validates_numericality_of    | :even                     | :even                     | -
|=====================================================================================================


==== Translations for the Active Record error_messages_for helper

If you are using the Active Record error_messages_for helper you will want to add translations for it. 

Rails ships with the following translations:

[source, ruby]
-------------------------------------------------------
en:
  activerecord:
    errors:
      template:
        header:
          one:   "1 error prohibited this {{model}} from being saved"
          other: "{{count}} errors prohibited this {{model}} from being saved"
        body:    "There were problems with the following fields:"
-------------------------------------------------------


=== Overview of other built-in methods that provide I18n support

Rails uses fixed strings and other localizations, such as format strings and other format information in a couple of helpers. Here's a brief overview.

==== ActionView helper methods

* distance_of_time_in_words translates and pluralizes its result and interpolates the number of seconds, minutes, hours and so on. See http://github.com/rails/rails/blob/master/actionpack/lib/action_view/locale/en.yml#L51[datetime.distance_in_words] translations.

* datetime_select and select_month use translated month names for populating the resulting select tag. See http://github.com/rails/rails/blob/master/activesupport/lib/active_support/locale/en.yml#L15[date.month_names] for translations. datetime_select also looks up the order option from http://github.com/rails/rails/blob/master/activesupport/lib/active_support/locale/en.yml#L18[date.order] (unless you pass the option explicitely). All date select helpers translate the prompt using the translations in the http://github.com/rails/rails/blob/master/actionpack/lib/action_view/locale/en.yml#L83[datetime.prompts] scope if applicable.

* The number_to_currency, number_with_precision, number_to_percentage, number_with_delimiter and humber_to_human_size helpers use the number format settings located in the http://github.com/rails/rails/blob/master/actionpack/lib/action_view/locale/en.yml#L2[number] scope.

==== Active Record methods

* human_name and human_attribute_name use translations for model names and attribute names if available in the http://github.com/rails/rails/blob/master/activerecord/lib/active_record/locale/en.yml#L43[activerecord.models] scope. They also support translations for inherited class names (e.g. for use with STI) as explained above in "Error message scopes".

* ActiveRecord::Errors#generate_message (which is used by Active Record validations but may also be used manually) uses human_name and human_attribute_name (see above). It also translates the error message and supports translations for inherited class names as explained above in "Error message scopes".

* ActiveRecord::Errors#full_messages prepends the attribute name to the error message using a separator that will be looked up from http://github.com/rails/rails/blob/master/actionpack/lib/action_view/locale/en.yml#L91[activerecord.errors.format.separator] (and defaults to ' ').

==== ActiveSupport methods

* Array#to_sentence uses format settings as given in the http://github.com/rails/rails/blob/master/activesupport/lib/active_support/locale/en.yml#L30[support.array] scope.


== Customize your I18n setup

=== Using different backends

For several reasons the shipped Simple backend only does the "simplest thing that ever could work" _for Ruby on Rails_ <<3>> ... which means that it is only guaranteed to work for English and, as a side effect, languages that are very similar to English. Also, the simple backend is only capable of reading translations but can not dynamically store them to any format.

That does not mean you're stuck with these limitations though. The Ruby I18n gem makes it very easy to exchange the Simple backend implementation with something else that fits better for your needs. E.g. you could exchange it with Globalize's Static backend:

[source, ruby]
-------------------------------------------------------
I18n.backend = Globalize::Backend::Static.new
-------------------------------------------------------

=== Using different exception handlers

The I18n API defines the following exceptions that will be raised by backends when the corresponding unexpected conditions occur:

[source, ruby]
-------------------------------------------------------
MissingTranslationData       # no translation was found for the requested key
InvalidLocale                # the locale set to I18n.locale is invalid (e.g. nil)
InvalidPluralizationData     # a count option was passed but the translation data is not suitable for pluralization
MissingInterpolationArgument # the translation expects an interpolation argument that has not been passed
ReservedInterpolationKey     # the translation contains a reserved interpolation variable name (i.e. one of: scope, default)
UnknownFileType              # the backend does not know how to handle a file type that was added to I18n.load_path
-------------------------------------------------------

The I18n API will catch all of these exceptions when they were thrown in the backend and pass them to the default_exception_handler method. This method will re-raise all exceptions except for MissingTranslationData exceptions. When a MissingTranslationData exception has been caught it will return the exception’s error message string containing the missing key/scope. 

The reason for this is that during development you'd usually want your views to still render even though a translation is missing. 

In other contexts you might want to change this behaviour though. E.g. the default exception handling does not allow to catch missing translations during automated tests easily. For this purpose a different exception handler can be specified. The specified exception handler must be a method on the I18n module:

[source, ruby]
-------------------------------------------------------
module I18n
  def just_raise_that_exception(*args)
    raise args.first
  end
end

I18n.exception_handler = :just_raise_that_exception
-------------------------------------------------------

This would re-raise all caught exceptions including MissingTranslationData.

Another example where the default behaviour is less desirable is the Rails TranslationHelper which provides the method #t (as well as #translate). When a MissingTranslationData exception occurs in this context the helper wraps the message into a span with the css class translation_missing.

To do so the helper forces I18n#translate to raise exceptions no matter what exception handler is defined by setting the :raise option:

[source, ruby]
-------------------------------------------------------
I18n.t :foo, :raise => true # always re-raises exceptions from the backend
-------------------------------------------------------


== Conclusion

At this point you hopefully have a good overview about how I18n support in Ruby on Rails works and are ready to start translating your project.

If you find anything missing or wrong in this guide please file a ticket on http://i18n.lighthouseapp.com/projects/14948-rails-i18n/overview[our issue tracker]. If you want to discuss certain portions or have questions please sign up to our http://groups.google.com/group/rails-i18n[mailinglist].


== Contributing to Rails I18n

I18n support in Ruby on Rails was introduced in the release 2.2 and is still evolving. The project follows the good Ruby on Rails development tradition of evolving solutions in plugins and real applications first and then cherry-picking the best bread of most widely useful features second for inclusion to the core.

Thus we encourage everybody to experiment with new ideas and features in plugins or other libraries and make them available to the community. (Don't forget to announce your work on our http://groups.google.com/group/rails-i18n[mailinglist]!)

If you find your own locale (language) missing from our http://github.com/svenfuchs/rails-i18n/tree/master/rails/locale[example translations data] repository for Ruby on Rails


== Resources

* http://rails-i18n.org[rails-i18n.org] - Homepage of the rails-i18n project. You can find lots of useful resources on the http://rails-i18n.org/wiki[wiki].
* http://groups.google.com/group/rails-i18n[rails-i18n Google group] - The project's mailinglist. 
* http://github.com/svenfuchs/rails-i18n/tree/master[Github: rails-i18n] - Code repository for the rails-i18n project. Most importantly you can find lots of http://github.com/svenfuchs/rails-i18n/tree/master/rails/locale[example translations] for Rails that should work for your application in most cases.
* http://i18n.lighthouseapp.com/projects/14948-rails-i18n/overview[Lighthouse: rails-i18n] - Issue tracker for the rails-i18n project.
* http://github.com/svenfuchs/i18n/tree/master[Github: i18n] - Code repository for the i18n gem.
* http://i18n.lighthouseapp.com/projects/14947-ruby-i18n/overview[Lighthouse: i18n] - Issue tracker for the i18n gem.


== Authors

* Sven Fuchs[http://www.workingwithrails.com/person/9963-sven-fuchs] (initial author)
* Karel Minarik[http://www.workingwithrails.com/person/7476-karel-mina-k]

If you found this guide useful please consider recommending its authors on http://www.workingwithrails.com[workingwithrails].


== Footnotes

[[[1]]] Or, to quote http://en.wikipedia.org/wiki/Internationalization_and_localization[Wikipedia]: _"Internationalization is the process of designing a software application so that it can be adapted to various languages and regions without engineering changes. Localization is the process of adapting software for a specific region or language by adding locale-specific components and translating text."_

[[[2]]] Other backends might allow or require to use other formats, e.g. a GetText backend might allow to read GetText files.

[[[3]]] One of these reasons is that we don't want to any unnecessary load for applications that do not need any I18n capabilities, so we need to keep the I18n library as simple as possible for English. Another reason is that it is virtually impossible to implement a one-fits-all solution for all problems related to I18n for all existing languages. So a solution that allows us to exchange the entire implementation easily is appropriate anyway. This also makes it much easier to experiment with custom features and extensions.


== Changelog ==

http://rails.lighthouseapp.com/projects/16213/tickets/23[Lighthouse ticket]