rails 4.2.6.rc1 → 5.2.8.1

Sign up to get free protection for your applications and to get access to all the features.

Potentially problematic release.


This version of rails might be problematic. Click here for more details.

Files changed (218) hide show
  1. checksums.yaml +5 -5
  2. data/README.md +24 -12
  3. metadata +54 -248
  4. data/guides/CHANGELOG.md +0 -73
  5. data/guides/Rakefile +0 -79
  6. data/guides/assets/images/akshaysurve.jpg +0 -0
  7. data/guides/assets/images/belongs_to.png +0 -0
  8. data/guides/assets/images/book_icon.gif +0 -0
  9. data/guides/assets/images/bullet.gif +0 -0
  10. data/guides/assets/images/chapters_icon.gif +0 -0
  11. data/guides/assets/images/check_bullet.gif +0 -0
  12. data/guides/assets/images/credits_pic_blank.gif +0 -0
  13. data/guides/assets/images/csrf.png +0 -0
  14. data/guides/assets/images/edge_badge.png +0 -0
  15. data/guides/assets/images/favicon.ico +0 -0
  16. data/guides/assets/images/feature_tile.gif +0 -0
  17. data/guides/assets/images/footer_tile.gif +0 -0
  18. data/guides/assets/images/fxn.png +0 -0
  19. data/guides/assets/images/getting_started/article_with_comments.png +0 -0
  20. data/guides/assets/images/getting_started/challenge.png +0 -0
  21. data/guides/assets/images/getting_started/confirm_dialog.png +0 -0
  22. data/guides/assets/images/getting_started/forbidden_attributes_for_new_article.png +0 -0
  23. data/guides/assets/images/getting_started/form_with_errors.png +0 -0
  24. data/guides/assets/images/getting_started/index_action_with_edit_link.png +0 -0
  25. data/guides/assets/images/getting_started/new_article.png +0 -0
  26. data/guides/assets/images/getting_started/rails_welcome.png +0 -0
  27. data/guides/assets/images/getting_started/routing_error_no_controller.png +0 -0
  28. data/guides/assets/images/getting_started/routing_error_no_route_matches.png +0 -0
  29. data/guides/assets/images/getting_started/show_action_for_articles.png +0 -0
  30. data/guides/assets/images/getting_started/template_is_missing_articles_new.png +0 -0
  31. data/guides/assets/images/getting_started/unknown_action_create_for_articles.png +0 -0
  32. data/guides/assets/images/getting_started/unknown_action_new_for_articles.png +0 -0
  33. data/guides/assets/images/grey_bullet.gif +0 -0
  34. data/guides/assets/images/habtm.png +0 -0
  35. data/guides/assets/images/has_many.png +0 -0
  36. data/guides/assets/images/has_many_through.png +0 -0
  37. data/guides/assets/images/has_one.png +0 -0
  38. data/guides/assets/images/has_one_through.png +0 -0
  39. data/guides/assets/images/header_backdrop.png +0 -0
  40. data/guides/assets/images/header_tile.gif +0 -0
  41. data/guides/assets/images/i18n/demo_html_safe.png +0 -0
  42. data/guides/assets/images/i18n/demo_localized_pirate.png +0 -0
  43. data/guides/assets/images/i18n/demo_translated_en.png +0 -0
  44. data/guides/assets/images/i18n/demo_translated_pirate.png +0 -0
  45. data/guides/assets/images/i18n/demo_translation_missing.png +0 -0
  46. data/guides/assets/images/i18n/demo_untranslated.png +0 -0
  47. data/guides/assets/images/icons/README +0 -5
  48. data/guides/assets/images/icons/callouts/1.png +0 -0
  49. data/guides/assets/images/icons/callouts/10.png +0 -0
  50. data/guides/assets/images/icons/callouts/11.png +0 -0
  51. data/guides/assets/images/icons/callouts/12.png +0 -0
  52. data/guides/assets/images/icons/callouts/13.png +0 -0
  53. data/guides/assets/images/icons/callouts/14.png +0 -0
  54. data/guides/assets/images/icons/callouts/15.png +0 -0
  55. data/guides/assets/images/icons/callouts/2.png +0 -0
  56. data/guides/assets/images/icons/callouts/3.png +0 -0
  57. data/guides/assets/images/icons/callouts/4.png +0 -0
  58. data/guides/assets/images/icons/callouts/5.png +0 -0
  59. data/guides/assets/images/icons/callouts/6.png +0 -0
  60. data/guides/assets/images/icons/callouts/7.png +0 -0
  61. data/guides/assets/images/icons/callouts/8.png +0 -0
  62. data/guides/assets/images/icons/callouts/9.png +0 -0
  63. data/guides/assets/images/icons/caution.png +0 -0
  64. data/guides/assets/images/icons/example.png +0 -0
  65. data/guides/assets/images/icons/home.png +0 -0
  66. data/guides/assets/images/icons/important.png +0 -0
  67. data/guides/assets/images/icons/next.png +0 -0
  68. data/guides/assets/images/icons/note.png +0 -0
  69. data/guides/assets/images/icons/prev.png +0 -0
  70. data/guides/assets/images/icons/tip.png +0 -0
  71. data/guides/assets/images/icons/up.png +0 -0
  72. data/guides/assets/images/icons/warning.png +0 -0
  73. data/guides/assets/images/nav_arrow.gif +0 -0
  74. data/guides/assets/images/oscardelben.jpg +0 -0
  75. data/guides/assets/images/polymorphic.png +0 -0
  76. data/guides/assets/images/radar.png +0 -0
  77. data/guides/assets/images/rails4_features.png +0 -0
  78. data/guides/assets/images/rails_guides_kindle_cover.jpg +0 -0
  79. data/guides/assets/images/rails_guides_logo.gif +0 -0
  80. data/guides/assets/images/rails_logo_remix.gif +0 -0
  81. data/guides/assets/images/session_fixation.png +0 -0
  82. data/guides/assets/images/tab_grey.gif +0 -0
  83. data/guides/assets/images/tab_info.gif +0 -0
  84. data/guides/assets/images/tab_note.gif +0 -0
  85. data/guides/assets/images/tab_red.gif +0 -0
  86. data/guides/assets/images/tab_yellow.gif +0 -0
  87. data/guides/assets/images/tab_yellow.png +0 -0
  88. data/guides/assets/images/vijaydev.jpg +0 -0
  89. data/guides/assets/javascripts/guides.js +0 -59
  90. data/guides/assets/javascripts/jquery.min.js +0 -4
  91. data/guides/assets/javascripts/responsive-tables.js +0 -43
  92. data/guides/assets/javascripts/syntaxhighlighter/shBrushAS3.js +0 -59
  93. data/guides/assets/javascripts/syntaxhighlighter/shBrushAppleScript.js +0 -75
  94. data/guides/assets/javascripts/syntaxhighlighter/shBrushBash.js +0 -59
  95. data/guides/assets/javascripts/syntaxhighlighter/shBrushCSharp.js +0 -65
  96. data/guides/assets/javascripts/syntaxhighlighter/shBrushColdFusion.js +0 -100
  97. data/guides/assets/javascripts/syntaxhighlighter/shBrushCpp.js +0 -97
  98. data/guides/assets/javascripts/syntaxhighlighter/shBrushCss.js +0 -91
  99. data/guides/assets/javascripts/syntaxhighlighter/shBrushDelphi.js +0 -55
  100. data/guides/assets/javascripts/syntaxhighlighter/shBrushDiff.js +0 -41
  101. data/guides/assets/javascripts/syntaxhighlighter/shBrushErlang.js +0 -52
  102. data/guides/assets/javascripts/syntaxhighlighter/shBrushGroovy.js +0 -67
  103. data/guides/assets/javascripts/syntaxhighlighter/shBrushJScript.js +0 -52
  104. data/guides/assets/javascripts/syntaxhighlighter/shBrushJava.js +0 -57
  105. data/guides/assets/javascripts/syntaxhighlighter/shBrushJavaFX.js +0 -58
  106. data/guides/assets/javascripts/syntaxhighlighter/shBrushPerl.js +0 -72
  107. data/guides/assets/javascripts/syntaxhighlighter/shBrushPhp.js +0 -88
  108. data/guides/assets/javascripts/syntaxhighlighter/shBrushPlain.js +0 -33
  109. data/guides/assets/javascripts/syntaxhighlighter/shBrushPowerShell.js +0 -74
  110. data/guides/assets/javascripts/syntaxhighlighter/shBrushPython.js +0 -64
  111. data/guides/assets/javascripts/syntaxhighlighter/shBrushRuby.js +0 -55
  112. data/guides/assets/javascripts/syntaxhighlighter/shBrushSass.js +0 -94
  113. data/guides/assets/javascripts/syntaxhighlighter/shBrushScala.js +0 -51
  114. data/guides/assets/javascripts/syntaxhighlighter/shBrushSql.js +0 -66
  115. data/guides/assets/javascripts/syntaxhighlighter/shBrushVb.js +0 -56
  116. data/guides/assets/javascripts/syntaxhighlighter/shBrushXml.js +0 -69
  117. data/guides/assets/javascripts/syntaxhighlighter/shCore.js +0 -17
  118. data/guides/assets/stylesheets/fixes.css +0 -16
  119. data/guides/assets/stylesheets/kindle.css +0 -11
  120. data/guides/assets/stylesheets/main.css +0 -713
  121. data/guides/assets/stylesheets/print.css +0 -52
  122. data/guides/assets/stylesheets/reset.css +0 -43
  123. data/guides/assets/stylesheets/responsive-tables.css +0 -50
  124. data/guides/assets/stylesheets/style.css +0 -13
  125. data/guides/assets/stylesheets/syntaxhighlighter/shCore.css +0 -226
  126. data/guides/assets/stylesheets/syntaxhighlighter/shCoreDefault.css +0 -328
  127. data/guides/assets/stylesheets/syntaxhighlighter/shCoreDjango.css +0 -331
  128. data/guides/assets/stylesheets/syntaxhighlighter/shCoreEclipse.css +0 -339
  129. data/guides/assets/stylesheets/syntaxhighlighter/shCoreEmacs.css +0 -324
  130. data/guides/assets/stylesheets/syntaxhighlighter/shCoreFadeToGrey.css +0 -328
  131. data/guides/assets/stylesheets/syntaxhighlighter/shCoreMDUltra.css +0 -324
  132. data/guides/assets/stylesheets/syntaxhighlighter/shCoreMidnight.css +0 -324
  133. data/guides/assets/stylesheets/syntaxhighlighter/shCoreRDark.css +0 -324
  134. data/guides/assets/stylesheets/syntaxhighlighter/shThemeDefault.css +0 -117
  135. data/guides/assets/stylesheets/syntaxhighlighter/shThemeDjango.css +0 -120
  136. data/guides/assets/stylesheets/syntaxhighlighter/shThemeEclipse.css +0 -128
  137. data/guides/assets/stylesheets/syntaxhighlighter/shThemeEmacs.css +0 -113
  138. data/guides/assets/stylesheets/syntaxhighlighter/shThemeFadeToGrey.css +0 -117
  139. data/guides/assets/stylesheets/syntaxhighlighter/shThemeMDUltra.css +0 -113
  140. data/guides/assets/stylesheets/syntaxhighlighter/shThemeMidnight.css +0 -113
  141. data/guides/assets/stylesheets/syntaxhighlighter/shThemeRDark.css +0 -113
  142. data/guides/assets/stylesheets/syntaxhighlighter/shThemeRailsGuides.css +0 -116
  143. data/guides/bug_report_templates/action_controller_gem.rb +0 -47
  144. data/guides/bug_report_templates/action_controller_master.rb +0 -54
  145. data/guides/bug_report_templates/active_record_gem.rb +0 -40
  146. data/guides/bug_report_templates/active_record_master.rb +0 -49
  147. data/guides/bug_report_templates/generic_gem.rb +0 -15
  148. data/guides/bug_report_templates/generic_master.rb +0 -26
  149. data/guides/rails_guides/generator.rb +0 -248
  150. data/guides/rails_guides/helpers.rb +0 -53
  151. data/guides/rails_guides/indexer.rb +0 -68
  152. data/guides/rails_guides/kindle.rb +0 -119
  153. data/guides/rails_guides/levenshtein.rb +0 -37
  154. data/guides/rails_guides/markdown/renderer.rb +0 -82
  155. data/guides/rails_guides/markdown.rb +0 -167
  156. data/guides/rails_guides.rb +0 -63
  157. data/guides/source/2_2_release_notes.md +0 -435
  158. data/guides/source/2_3_release_notes.md +0 -621
  159. data/guides/source/3_0_release_notes.md +0 -611
  160. data/guides/source/3_1_release_notes.md +0 -559
  161. data/guides/source/3_2_release_notes.md +0 -568
  162. data/guides/source/4_0_release_notes.md +0 -279
  163. data/guides/source/4_1_release_notes.md +0 -730
  164. data/guides/source/4_2_release_notes.md +0 -877
  165. data/guides/source/_license.html.erb +0 -2
  166. data/guides/source/_welcome.html.erb +0 -23
  167. data/guides/source/action_controller_overview.md +0 -1192
  168. data/guides/source/action_mailer_basics.md +0 -757
  169. data/guides/source/action_view_overview.md +0 -1561
  170. data/guides/source/active_job_basics.md +0 -339
  171. data/guides/source/active_model_basics.md +0 -554
  172. data/guides/source/active_record_basics.md +0 -374
  173. data/guides/source/active_record_callbacks.md +0 -413
  174. data/guides/source/active_record_migrations.md +0 -1018
  175. data/guides/source/active_record_postgresql.md +0 -433
  176. data/guides/source/active_record_querying.md +0 -1781
  177. data/guides/source/active_record_validations.md +0 -1179
  178. data/guides/source/active_support_core_extensions.md +0 -3857
  179. data/guides/source/active_support_instrumentation.md +0 -488
  180. data/guides/source/api_documentation_guidelines.md +0 -361
  181. data/guides/source/asset_pipeline.md +0 -1304
  182. data/guides/source/association_basics.md +0 -2245
  183. data/guides/source/autoloading_and_reloading_constants.md +0 -1311
  184. data/guides/source/caching_with_rails.md +0 -379
  185. data/guides/source/command_line.md +0 -625
  186. data/guides/source/configuring.md +0 -1072
  187. data/guides/source/contributing_to_ruby_on_rails.md +0 -628
  188. data/guides/source/credits.html.erb +0 -80
  189. data/guides/source/debugging_rails_applications.md +0 -861
  190. data/guides/source/development_dependencies_install.md +0 -289
  191. data/guides/source/documents.yaml +0 -205
  192. data/guides/source/engines.md +0 -1412
  193. data/guides/source/form_helpers.md +0 -1024
  194. data/guides/source/generators.md +0 -676
  195. data/guides/source/getting_started.md +0 -2086
  196. data/guides/source/i18n.md +0 -1087
  197. data/guides/source/index.html.erb +0 -28
  198. data/guides/source/initialization.md +0 -704
  199. data/guides/source/kindle/copyright.html.erb +0 -1
  200. data/guides/source/kindle/layout.html.erb +0 -27
  201. data/guides/source/kindle/rails_guides.opf.erb +0 -52
  202. data/guides/source/kindle/toc.html.erb +0 -24
  203. data/guides/source/kindle/toc.ncx.erb +0 -64
  204. data/guides/source/kindle/welcome.html.erb +0 -5
  205. data/guides/source/layout.html.erb +0 -140
  206. data/guides/source/layouts_and_rendering.md +0 -1227
  207. data/guides/source/maintenance_policy.md +0 -78
  208. data/guides/source/nested_model_forms.md +0 -228
  209. data/guides/source/plugins.md +0 -444
  210. data/guides/source/rails_application_templates.md +0 -266
  211. data/guides/source/rails_on_rack.md +0 -336
  212. data/guides/source/routing.md +0 -1155
  213. data/guides/source/ruby_on_rails_guides_guidelines.md +0 -127
  214. data/guides/source/security.md +0 -1024
  215. data/guides/source/testing.md +0 -1132
  216. data/guides/source/upgrading_ruby_on_rails.md +0 -1186
  217. data/guides/source/working_with_javascript_in_rails.md +0 -407
  218. data/guides/w3c_validator.rb +0 -97
@@ -1,1087 +0,0 @@
1
- Rails Internationalization (I18n) API
2
- =====================================
3
-
4
- 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 for **providing multi-language support** in your application.
5
-
6
- The process of "internationalization" usually means to abstract all strings and other locale specific bits (such as date or currency formats) out of your application. The process of "localization" means to provide translations and localized formats for these bits.[^1]
7
-
8
- So, in the process of _internationalizing_ your Rails application you have to:
9
-
10
- * Ensure you have support for i18n.
11
- * Tell Rails where to find locale dictionaries.
12
- * Tell Rails how to set, preserve and switch locales.
13
-
14
- In the process of _localizing_ your application you'll probably want to do the following three things:
15
-
16
- * Replace or supplement Rails' default locale - e.g. date and time formats, month names, Active Record model names, etc.
17
- * Abstract strings in your application into keyed dictionaries - e.g. flash messages, static text in your views, etc.
18
- * Store the resulting dictionaries somewhere.
19
-
20
- This guide will walk you through the I18n API and contains a tutorial on how to internationalize a Rails application from the start.
21
-
22
- After reading this guide, you will know:
23
-
24
- * How I18n works in Ruby on Rails
25
- * How to correctly use I18n into a RESTful application in various ways
26
- * How to use I18n to translate ActiveRecord errors or ActionMailer E-mail subjects
27
- * Some other tools to go further with the translation process of your application
28
-
29
- --------------------------------------------------------------------------------
30
-
31
- NOTE: The Ruby I18n framework provides you with all necessary means for internationalization/localization of your Rails application. You may, also use various gems available to add additional functionality or features. See the [rails-i18n gem](https://github.com/svenfuchs/rails-i18n) for more information.
32
-
33
- How I18n in Ruby on Rails Works
34
- -------------------------------
35
-
36
- Internationalization is a complex problem. Natural languages differ in so many ways (e.g. 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:
37
-
38
- * providing support for English and similar languages out of the box
39
- * making it easy to customize and extend everything for other languages
40
-
41
- As part of this solution, **every static string in the Rails framework** - e.g. Active Record validation messages, time and date formats - **has been internationalized**, so _localization_ of a Rails application means "over-riding" these defaults.
42
-
43
- ### The Overall Architecture of the Library
44
-
45
- Thus, the Ruby I18n gem is split into two parts:
46
-
47
- * The public API of the i18n framework - a Ruby module with public methods that define how the library works
48
- * A default backend (which is intentionally named _Simple_ backend) that implements these methods
49
-
50
- 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.
51
-
52
- 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.
53
-
54
- ### The Public I18n API
55
-
56
- The most important methods of the I18n API are:
57
-
58
- ```ruby
59
- translate # Lookup text translations
60
- localize # Localize Date and Time objects to local formats
61
- ```
62
-
63
- These have the aliases #t and #l so you can use them like this:
64
-
65
- ```ruby
66
- I18n.t 'store.title'
67
- I18n.l Time.now
68
- ```
69
-
70
- There are also attribute readers and writers for the following attributes:
71
-
72
- ```ruby
73
- load_path # Announce your custom translation files
74
- locale # Get and set the current locale
75
- default_locale # Get and set the default locale
76
- exception_handler # Use a different exception_handler
77
- backend # Use a different backend
78
- ```
79
-
80
- So, let's internationalize a simple Rails application from the ground up in the next chapters!
81
-
82
- Setup the Rails Application for Internationalization
83
- ----------------------------------------------------
84
-
85
- There are just a few simple steps to get up and running with I18n support for your application.
86
-
87
- ### Configure the I18n Module
88
-
89
- 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.
90
-
91
- Rails adds all `.rb` and `.yml` files from the `config/locales` directory to your **translations load path**, automatically.
92
-
93
- The default `en.yml` locale in this directory contains a sample pair of translation strings:
94
-
95
- ```yaml
96
- en:
97
- hello: "Hello world"
98
- ```
99
-
100
- This means, that in the `:en` locale, the key _hello_ will map to the _Hello world_ string. Every string inside Rails is internationalized in this way, see for instance Active Model validation messages in the [`activemodel/lib/active_model/locale/en.yml`](https://github.com/rails/rails/blob/master/activemodel/lib/active_model/locale/en.yml) file or time and date formats in the [`activesupport/lib/active_support/locale/en.yml`](https://github.com/rails/rails/blob/master/activesupport/lib/active_support/locale/en.yml) file. You can use YAML or standard Ruby Hashes to store translations in the default (Simple) backend.
101
-
102
- The I18n library will use **English** as a **default locale**, i.e. if you don't set a different locale, `:en` will be used for looking up translations.
103
-
104
- NOTE: The i18n library takes a **pragmatic approach** to locale keys (after [some discussion](http://groups.google.com/group/rails-i18n/browse_thread/thread/14dede2c7dbe9470/80eec34395f64f3c?hl=en)), including only the _locale_ ("language") part, like `:en`, `:pl`, not the _region_ part, like `:en-US` or `:en-GB`, which are traditionally used for separating "languages" and "regional setting" or "dialects". Many international applications use only the "language" element of a locale such as `:cs`, `:th` or `:es` (for Czech, Thai and Spanish). However, there are also regional differences within different language groups that may be important. For instance, in the `:en-US` locale you would have $ as a currency symbol, while in `:en-GB`, you would have £. Nothing stops you from separating regional and other settings in this way: you just have to provide full "English - United Kingdom" locale in a `:en-GB` dictionary. Few gems such as [Globalize3](https://github.com/globalize/globalize) may help you implement it.
105
-
106
- 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.
107
-
108
- 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.
109
-
110
- The default `application.rb` file has instructions on how to add locales from another directory and how to set a different default locale. Just uncomment and edit the specific lines.
111
-
112
- ```ruby
113
- # The default locale is :en and all translations from config/locales/*.rb,yml are auto loaded.
114
- # config.i18n.load_path += Dir[Rails.root.join('my', 'locales', '*.{rb,yml}').to_s]
115
- # config.i18n.default_locale = :de
116
- ```
117
-
118
- ### Optional: Custom I18n Configuration Setup
119
-
120
- For the sake of completeness, let's mention that if you do not want to use the `application.rb` file for some reason, you can always wire up things manually, too.
121
-
122
- 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:
123
-
124
- ```ruby
125
- # in config/initializers/locale.rb
126
-
127
- # tell the I18n library where to find your translations
128
- I18n.load_path += Dir[Rails.root.join('lib', 'locale', '*.{rb,yml}')]
129
-
130
- # set default locale to something other than :en
131
- I18n.default_locale = :pt
132
- ```
133
-
134
- ### Setting and Passing the Locale
135
-
136
- 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 `application.rb` or an initializer as shown above, and it will persist through the requests.
137
-
138
- 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.
139
-
140
- WARNING: You may be tempted to store the chosen locale in a _session_ or a *cookie*. However, **do not do this**. The locale should be transparent and a part of the URL. This way you won't break people's basic assumptions about the web itself: if you send a URL to a friend, they should see the same page and content as you. A fancy word for this would be that you're being [*RESTful*](http://en.wikipedia.org/wiki/Representational_State_Transfer). Read more about the RESTful approach in [Stefan Tilkov's articles](http://www.infoq.com/articles/rest-introduction). Sometimes there are exceptions to this rule and those are discussed below.
141
-
142
- The _setting part_ is easy. You can set the locale in a `before_action` in the `ApplicationController` like this:
143
-
144
- ```ruby
145
- before_action :set_locale
146
-
147
- def set_locale
148
- I18n.locale = params[:locale] || I18n.default_locale
149
- end
150
- ```
151
-
152
- This requires you to pass the locale as a URL query parameter as in `http://example.com/books?locale=pt`. (This is, for example, Google's approach.) So `http://localhost:3000?locale=pt` will load the Portuguese localization, whereas `http://localhost:3000?locale=de` would load the German localization, and so on. You may skip the next section and head over to the **Internationalize your application** section, if you want to try things out by manually placing the locale in the URL and reloading the page.
153
-
154
- Of course, you probably don't want to manually include the locale in every URL all over your application, or want the URLs look differently, e.g. the usual `http://example.com/pt/books` versus `http://example.com/en/books`. Let's discuss the different options you have.
155
-
156
- ### Setting the Locale from the Domain Name
157
-
158
- 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 the English (or default) locale, and `www.example.es` to load the Spanish locale. Thus the _top-level domain name_ is used for locale setting. This has several advantages:
159
-
160
- * The locale is an _obvious_ part of the URL.
161
- * People intuitively grasp in which language the content will be displayed.
162
- * It is very trivial to implement in Rails.
163
- * Search engines seem to like that content in different languages lives at different, inter-linked domains.
164
-
165
- You can implement it like this in your `ApplicationController`:
166
-
167
- ```ruby
168
- before_action :set_locale
169
-
170
- def set_locale
171
- I18n.locale = extract_locale_from_tld || I18n.default_locale
172
- end
173
-
174
- # Get locale from top-level domain or return nil if such locale is not available
175
- # You have to put something like:
176
- # 127.0.0.1 application.com
177
- # 127.0.0.1 application.it
178
- # 127.0.0.1 application.pl
179
- # in your /etc/hosts file to try this out locally
180
- def extract_locale_from_tld
181
- parsed_locale = request.host.split('.').last
182
- I18n.available_locales.map(&:to_s).include?(parsed_locale) ? parsed_locale : nil
183
- end
184
- ```
185
-
186
- We can also set the locale from the _subdomain_ in a very similar way:
187
-
188
- ```ruby
189
- # Get locale code from request subdomain (like http://it.application.local:3000)
190
- # You have to put something like:
191
- # 127.0.0.1 gr.application.local
192
- # in your /etc/hosts file to try this out locally
193
- def extract_locale_from_subdomain
194
- parsed_locale = request.subdomains.first
195
- I18n.available_locales.map(&:to_s).include?(parsed_locale) ? parsed_locale : nil
196
- end
197
- ```
198
-
199
- If your application includes a locale switching menu, you would then have something like this in it:
200
-
201
- ```ruby
202
- link_to("Deutsch", "#{APP_CONFIG[:deutsch_website_url]}#{request.env['REQUEST_URI']}")
203
- ```
204
-
205
- assuming you would set `APP_CONFIG[:deutsch_website_url]` to some value like `http://www.application.de`.
206
-
207
- This solution has aforementioned advantages, however, you may not be able or may not want to provide different localizations ("language versions") on different domains. The most obvious solution would be to include locale code in the URL params (or request path).
208
-
209
- ### Setting the Locale from the URL Params
210
-
211
- The most usual way of setting (and passing) the locale would be to include it in URL params, as we did in the `I18n.locale = params[:locale]` _before_action_ in the first example. We would like to have URLs like `www.example.com/books?locale=ja` or `www.example.com/ja/books` in this case.
212
-
213
- This approach has almost the same set of advantages as setting the locale from the domain name: namely that it's RESTful and in accord with the rest of the World Wide Web. It does require a little bit more work to implement, though.
214
-
215
- Getting the locale from `params` and setting it accordingly is not hard; including it in every URL and thus **passing it through the requests** is. To include an explicit option in every URL, e.g. `link_to(books_url(locale: I18n.locale))`, would be tedious and probably impossible, of course.
216
-
217
- Rails contains infrastructure for "centralizing dynamic decisions about the URLs" in its [`ApplicationController#default_url_options`](http://api.rubyonrails.org/classes/ActionDispatch/Routing/Mapper/Base.html#method-i-default_url_options), which is useful precisely in this scenario: it enables us to set "defaults" for [`url_for`](http://api.rubyonrails.org/classes/ActionDispatch/Routing/UrlFor.html#method-i-url_for) and helper methods dependent on it (by implementing/overriding this method).
218
-
219
- We can include something like this in our `ApplicationController` then:
220
-
221
- ```ruby
222
- # app/controllers/application_controller.rb
223
- def default_url_options(options = {})
224
- { locale: I18n.locale }.merge options
225
- end
226
- ```
227
-
228
- Every helper method dependent on `url_for` (e.g. helpers for named routes like `root_path` or `root_url`, resource routes like `books_path` or `books_url`, etc.) will now **automatically include the locale in the query string**, like this: `http://localhost:3001/?locale=ja`.
229
-
230
- You may be satisfied with this. It does impact the readability of URLs, though, when the locale "hangs" at the end of every URL in your application. Moreover, from the architectural standpoint, locale is usually hierarchically above the other parts of the application domain: and URLs should reflect this.
231
-
232
- You probably want URLs to look like this: `www.example.com/en/books` (which loads the English locale) and `www.example.com/nl/books` (which loads the Dutch locale). This is achievable with the "over-riding `default_url_options`" strategy from above: you just have to set up your routes with [`scoping`](http://api.rubyonrails.org/classes/ActionDispatch/Routing/Mapper/Scoping.html) option in this way:
233
-
234
- ```ruby
235
- # config/routes.rb
236
- scope "/:locale" do
237
- resources :books
238
- end
239
- ```
240
-
241
- Now, when you call the `books_path` method you should get `"/en/books"` (for the default locale). An URL like `http://localhost:3001/nl/books` should load the Dutch locale, then, and following calls to `books_path` should return `"/nl/books"` (because the locale changed).
242
-
243
- If you don't want to force the use of a locale in your routes you can use an optional path scope (denoted by the parentheses) like so:
244
-
245
- ```ruby
246
- # config/routes.rb
247
- scope "(:locale)", locale: /en|nl/ do
248
- resources :books
249
- end
250
- ```
251
-
252
- With this approach you will not get a `Routing Error` when accessing your resources such as `http://localhost:3001/books` without a locale. This is useful for when you want to use the default locale when one is not specified.
253
-
254
- Of course, you need to take special care of the root URL (usually "homepage" or "dashboard") of your application. An URL like `http://localhost:3001/nl` will not work automatically, because the `root to: "books#index"` declaration in your `routes.rb` doesn't take locale into account. (And rightly so: there's only one "root" URL.)
255
-
256
- You would probably need to map URLs like these:
257
-
258
- ```ruby
259
- # config/routes.rb
260
- get '/:locale' => 'dashboard#index'
261
- ```
262
-
263
- Do take special care about the **order of your routes**, so this route declaration does not "eat" other ones. (You may want to add it directly before the `root :to` declaration.)
264
-
265
- NOTE: Have a look at various gems which simplify working with routes: [routing_filter](https://github.com/svenfuchs/routing-filter/tree/master), [rails-translate-routes](https://github.com/francesc/rails-translate-routes), [route_translator](https://github.com/enriclluelles/route_translator).
266
-
267
- ### Setting the Locale from the Client Supplied Information
268
-
269
- In specific cases, it would make sense to set the locale from client-supplied information, i.e. not from the URL. This information may come for example from the users' preferred language (set in their browser), can be based on the users' geographical location inferred from their IP, or users can provide it simply by choosing the locale in your application interface and saving it to their profile. This approach is more suitable for web-based applications or services, not for websites - see the box about _sessions_, _cookies_ and RESTful architecture above.
270
-
271
-
272
- #### Using `Accept-Language`
273
-
274
- One source of client supplied information would be an `Accept-Language` HTTP header. People may [set this in their browser](http://www.w3.org/International/questions/qa-lang-priorities) or other clients (such as _curl_).
275
-
276
- A trivial implementation of using an `Accept-Language` header would be:
277
-
278
- ```ruby
279
- def set_locale
280
- logger.debug "* Accept-Language: #{request.env['HTTP_ACCEPT_LANGUAGE']}"
281
- I18n.locale = extract_locale_from_accept_language_header
282
- logger.debug "* Locale set to '#{I18n.locale}'"
283
- end
284
-
285
- private
286
- def extract_locale_from_accept_language_header
287
- request.env['HTTP_ACCEPT_LANGUAGE'].scan(/^[a-z]{2}/).first
288
- end
289
- ```
290
-
291
- Of course, in a production environment you would need much more robust code, and could use a gem such as Iain Hecker's [http_accept_language](https://github.com/iain/http_accept_language/tree/master) or even Rack middleware such as Ryan Tomayko's [locale](https://github.com/rack/rack-contrib/blob/master/lib/rack/contrib/locale.rb).
292
-
293
- #### Using GeoIP (or Similar) Database
294
-
295
- Another way of choosing the locale from client information would be to use a database for mapping the client IP to the region, such as [GeoIP Lite Country](http://www.maxmind.com/app/geolitecountry). The mechanics of the code would be very similar to the code above - you would need to query the database for the user's IP, and look up your preferred locale for the country/region/city returned.
296
-
297
- #### User Profile
298
-
299
- You can also provide users of your application with means to set (and possibly over-ride) the locale in your application interface, as well. Again, mechanics for this approach would be very similar to the code above - you'd probably let users choose a locale from a dropdown list and save it to their profile in the database. Then you'd set the locale to this value.
300
-
301
- Internationalizing your Application
302
- -----------------------------------
303
-
304
- OK! Now you've initialized I18n support for your Ruby on Rails application and told it which locale to use and how to preserve it between requests. With that in place, you're now ready for the really interesting stuff.
305
-
306
- Let's _internationalize_ our application, i.e. abstract every locale-specific parts, and then _localize_ it, i.e. provide necessary translations for these abstracts.
307
-
308
- You most probably have something like this in one of your applications:
309
-
310
- ```ruby
311
- # config/routes.rb
312
- Rails.application.routes.draw do
313
- root to: "home#index"
314
- end
315
- ```
316
-
317
- ```ruby
318
- # app/controllers/application_controller.rb
319
- class ApplicationController < ActionController::Base
320
- before_action :set_locale
321
-
322
- def set_locale
323
- I18n.locale = params[:locale] || I18n.default_locale
324
- end
325
- end
326
- ```
327
-
328
- ```ruby
329
- # app/controllers/home_controller.rb
330
- class HomeController < ApplicationController
331
- def index
332
- flash[:notice] = "Hello Flash"
333
- end
334
- end
335
- ```
336
-
337
- ```html+erb
338
- # app/views/home/index.html.erb
339
- <h1>Hello World</h1>
340
- <p><%= flash[:notice] %></p>
341
- ```
342
-
343
- ![rails i18n demo untranslated](images/i18n/demo_untranslated.png)
344
-
345
- ### Adding Translations
346
-
347
- 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:
348
-
349
- ```ruby
350
- # app/controllers/home_controller.rb
351
- class HomeController < ApplicationController
352
- def index
353
- flash[:notice] = t(:hello_flash)
354
- end
355
- end
356
- ```
357
-
358
- ```html+erb
359
- # app/views/home/index.html.erb
360
- <h1><%=t :hello_world %></h1>
361
- <p><%= flash[:notice] %></p>
362
- ```
363
-
364
- When you now render this view, it will show an error message which tells you that the translations for the keys `:hello_world` and `:hello_flash` are missing.
365
-
366
- ![rails i18n demo translation missing](images/i18n/demo_translation_missing.png)
367
-
368
- 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 `<span class="translation_missing">`.
369
-
370
- So let's add the missing translations into the dictionary files (i.e. do the "localization" part):
371
-
372
- ```yaml
373
- # config/locales/en.yml
374
- en:
375
- hello_world: Hello world!
376
- hello_flash: Hello flash!
377
-
378
- # config/locales/pirate.yml
379
- pirate:
380
- hello_world: Ahoy World
381
- hello_flash: Ahoy Flash
382
- ```
383
-
384
- There you go. Because you haven't changed the default_locale, I18n will use English. Your application now shows:
385
-
386
- ![rails i18n demo translated to English](images/i18n/demo_translated_en.png)
387
-
388
- And when you change the URL to pass the pirate locale (`http://localhost:3000?locale=pirate`), you'll get:
389
-
390
- ![rails i18n demo translated to pirate](images/i18n/demo_translated_pirate.png)
391
-
392
- NOTE: You need to restart the server when you add new locale files.
393
-
394
- You may use YAML (`.yml`) or plain Ruby (`.rb`) files for storing your translations in SimpleStore. YAML is the preferred option among Rails developers. However, it has one big disadvantage. YAML is very sensitive to whitespace and special characters, so the application may not load your dictionary properly. Ruby files will crash your application on first request, so you may easily find what's wrong. (If you encounter any "weird issues" with YAML dictionaries, try putting the relevant portion of your dictionary into a Ruby file.)
395
-
396
- ### Passing variables to translations
397
-
398
- You can use variables in the translation messages and pass their values from the view.
399
-
400
- ```erb
401
- # app/views/home/index.html.erb
402
- <%=t 'greet_username', user: "Bill", message: "Goodbye" %>
403
- ```
404
-
405
- ```yaml
406
- # config/locales/en.yml
407
- en:
408
- greet_username: "%{message}, %{user}!"
409
- ```
410
-
411
- ### Adding Date/Time Formats
412
-
413
- OK! Now 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.
414
-
415
- ```erb
416
- # app/views/home/index.html.erb
417
- <h1><%=t :hello_world %></h1>
418
- <p><%= flash[:notice] %></p
419
- <p><%= l Time.now, format: :short %></p>
420
- ```
421
-
422
- And in our pirate translations file let's add a time format (it's already there in Rails' defaults for English):
423
-
424
- ```yaml
425
- # config/locales/pirate.yml
426
- pirate:
427
- time:
428
- formats:
429
- short: "arrrround %H'ish"
430
- ```
431
-
432
- So that would give you:
433
-
434
- ![rails i18n demo localized time to pirate](images/i18n/demo_localized_pirate.png)
435
-
436
- TIP: Right now you might need to add some more date/time formats in order to make the I18n backend work as expected (at least for the 'pirate' locale). Of course, there's a great chance that somebody already did all the work by **translating Rails' defaults for your locale**. See the [rails-i18n repository at GitHub](https://github.com/svenfuchs/rails-i18n/tree/master/rails/locale) for an archive of various locale files. When you put such file(s) in `config/locales/` directory, they will automatically be ready for use.
437
-
438
- ### Inflection Rules For Other Locales
439
-
440
- Rails allows you to define inflection rules (such as rules for singularization and pluralization) for locales other than English. In `config/initializers/inflections.rb`, you can define these rules for multiple locales. The initializer contains a default example for specifying additional rules for English; follow that format for other locales as you see fit.
441
-
442
- ### Localized Views
443
-
444
- Let's say you have a _BooksController_ in your application. Your _index_ action renders content in `app/views/books/index.html.erb` template. When you put a _localized variant_ of this template: `index.es.html.erb` in the same directory, Rails will render content in this template, when the locale is set to `:es`. When the locale is set to the default locale, the generic `index.html.erb` view will be used. (Future Rails versions may well bring this _automagic_ localization to assets in `public`, etc.)
445
-
446
- You can make use of this feature, e.g. when working with a large amount of static content, which would be clumsy to put inside YAML or Ruby dictionaries. Bear in mind, though, that any change you would like to do later to the template must be propagated to all of them.
447
-
448
- ### Organization of Locale Files
449
-
450
- When you are using the default SimpleStore shipped with the i18n library, dictionaries are stored in plain-text files on the disc. Putting translations for all parts of your application in one file per locale could be hard to manage. You can store these files in a hierarchy which makes sense to you.
451
-
452
- For example, your `config/locales` directory could look like this:
453
-
454
- ```
455
- |-defaults
456
- |---es.rb
457
- |---en.rb
458
- |-models
459
- |---book
460
- |-----es.rb
461
- |-----en.rb
462
- |-views
463
- |---defaults
464
- |-----es.rb
465
- |-----en.rb
466
- |---books
467
- |-----es.rb
468
- |-----en.rb
469
- |---users
470
- |-----es.rb
471
- |-----en.rb
472
- |---navigation
473
- |-----es.rb
474
- |-----en.rb
475
- ```
476
-
477
- This way, you can separate model and model attribute names from text inside views, and all of this from the "defaults" (e.g. date and time formats). Other stores for the i18n library could provide different means of such separation.
478
-
479
- NOTE: The default locale loading mechanism in Rails does not load locale files in nested dictionaries, like we have here. So, for this to work, we must explicitly tell Rails to look further:
480
-
481
- ```ruby
482
- # config/application.rb
483
- config.i18n.load_path += Dir[Rails.root.join('config', 'locales', '**', '*.{rb,yml}')]
484
-
485
- ```
486
-
487
- Overview of the I18n API Features
488
- ---------------------------------
489
-
490
- You should have good understanding of using the i18n library now, knowing all necessary aspects of internationalizing a basic Rails application. In the following chapters, we'll cover it's features in more depth.
491
-
492
- These chapters will show examples using both the `I18n.translate` method as well as the [`translate` view helper method](http://api.rubyonrails.org/classes/ActionView/Helpers/TranslationHelper.html#method-i-translate) (noting the additional feature provide by the view helper method).
493
-
494
- Covered are features like these:
495
-
496
- * looking up translations
497
- * interpolating data into translations
498
- * pluralizing translations
499
- * using safe HTML translations (view helper method only)
500
- * localizing dates, numbers, currency, etc.
501
-
502
- ### Looking up Translations
503
-
504
- #### Basic Lookup, Scopes and Nested Keys
505
-
506
- Translations are looked up by keys which can be both Symbols or Strings, so these calls are equivalent:
507
-
508
- ```ruby
509
- I18n.t :message
510
- I18n.t 'message'
511
- ```
512
-
513
- The `translate` method also takes a `:scope` option which can contain one or more additional keys that will be used to specify a "namespace" or scope for a translation key:
514
-
515
- ```ruby
516
- I18n.t :record_invalid, scope: [:activerecord, :errors, :messages]
517
- ```
518
-
519
- This looks up the `:record_invalid` message in the Active Record error messages.
520
-
521
- Additionally, both the key and scopes can be specified as dot-separated keys as in:
522
-
523
- ```ruby
524
- I18n.translate "activerecord.errors.messages.record_invalid"
525
- ```
526
-
527
- Thus the following calls are equivalent:
528
-
529
- ```ruby
530
- I18n.t 'activerecord.errors.messages.record_invalid'
531
- I18n.t 'errors.messages.record_invalid', scope: :active_record
532
- I18n.t :record_invalid, scope: 'activerecord.errors.messages'
533
- I18n.t :record_invalid, scope: [:activerecord, :errors, :messages]
534
- ```
535
-
536
- #### Defaults
537
-
538
- When a `:default` option is given, its value will be returned if the translation is missing:
539
-
540
- ```ruby
541
- I18n.t :missing, default: 'Not here'
542
- # => 'Not here'
543
- ```
544
-
545
- 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.
546
-
547
- 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:
548
-
549
- ```ruby
550
- I18n.t :missing, default: [:also_missing, 'Not here']
551
- # => 'Not here'
552
- ```
553
-
554
- #### Bulk and Namespace Lookup
555
-
556
- To look up multiple translations at once, an array of keys can be passed:
557
-
558
- ```ruby
559
- I18n.t [:odd, :even], scope: 'errors.messages'
560
- # => ["must be odd", "must be even"]
561
- ```
562
-
563
- Also, a key can translate to a (potentially nested) hash of grouped translations. E.g., one can receive _all_ Active Record error messages as a Hash with:
564
-
565
- ```ruby
566
- I18n.t 'activerecord.errors.messages'
567
- # => {:inclusion=>"is not included in the list", :exclusion=> ... }
568
- ```
569
-
570
- #### "Lazy" Lookup
571
-
572
- Rails implements a convenient way to look up the locale inside _views_. When you have the following dictionary:
573
-
574
- ```yaml
575
- es:
576
- books:
577
- index:
578
- title: "Título"
579
- ```
580
-
581
- you can look up the `books.index.title` value **inside** `app/views/books/index.html.erb` template like this (note the dot):
582
-
583
- ```erb
584
- <%= t '.title' %>
585
- ```
586
-
587
- NOTE: Automatic translation scoping by partial is only available from the `translate` view helper method.
588
-
589
- ### Interpolation
590
-
591
- 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.
592
-
593
- All options besides `:default` and `:scope` that are passed to `#translate` will be interpolated to the translation:
594
-
595
- ```ruby
596
- I18n.backend.store_translations :en, thanks: 'Thanks %{name}!'
597
- I18n.translate :thanks, name: 'Jeremy'
598
- # => 'Thanks Jeremy!'
599
- ```
600
-
601
- If a translation uses `:default` or `:scope` as an interpolation variable, an `I18n::ReservedInterpolationKey` exception is raised. If a translation expects an interpolation variable, but this has not been passed to `#translate`, an `I18n::MissingInterpolationArgument` exception is raised.
602
-
603
- ### Pluralization
604
-
605
- In English there are only one singular and one plural form for a given string, e.g. "1 message" and "2 messages". Other languages ([Arabic](http://unicode.org/repos/cldr-tmp/trunk/diff/supplemental/language_plural_rules.html#ar), [Japanese](http://unicode.org/repos/cldr-tmp/trunk/diff/supplemental/language_plural_rules.html#ja), [Russian](http://unicode.org/repos/cldr-tmp/trunk/diff/supplemental/language_plural_rules.html#ru) and many more) have different grammars that have additional or fewer [plural forms](http://unicode.org/repos/cldr-tmp/trunk/diff/supplemental/language_plural_rules.html). Thus, the I18n API provides a flexible pluralization feature.
606
-
607
- 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:
608
-
609
- ```ruby
610
- I18n.backend.store_translations :en, inbox: {
611
- one: 'one message',
612
- other: '%{count} messages'
613
- }
614
- I18n.translate :inbox, count: 2
615
- # => '2 messages'
616
-
617
- I18n.translate :inbox, count: 1
618
- # => 'one message'
619
- ```
620
-
621
- The algorithm for pluralizations in `:en` is as simple as:
622
-
623
- ```ruby
624
- entry[count == 1 ? 0 : 1]
625
- ```
626
-
627
- I.e. the translation denoted as `:one` is regarded as singular, the other is used as plural (including the count being zero).
628
-
629
- If the lookup for the key does not return a Hash suitable for pluralization, an `18n::InvalidPluralizationData` exception is raised.
630
-
631
- ### Setting and Passing a Locale
632
-
633
- 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`.
634
-
635
- If no locale is passed, `I18n.locale` is used:
636
-
637
- ```ruby
638
- I18n.locale = :de
639
- I18n.t :foo
640
- I18n.l Time.now
641
- ```
642
-
643
- Explicitly passing a locale:
644
-
645
- ```ruby
646
- I18n.t :foo, locale: :de
647
- I18n.l Time.now, locale: :de
648
- ```
649
-
650
- The `I18n.locale` defaults to `I18n.default_locale` which defaults to :`en`. The default locale can be set like this:
651
-
652
- ```ruby
653
- I18n.default_locale = :de
654
- ```
655
-
656
- ### Using Safe HTML Translations
657
-
658
- Keys with a '_html' suffix and keys named 'html' are marked as HTML safe. When you use them in views the HTML will not be escaped.
659
-
660
- ```yaml
661
- # config/locales/en.yml
662
- en:
663
- welcome: <b>welcome!</b>
664
- hello_html: <b>hello!</b>
665
- title:
666
- html: <b>title!</b>
667
- ```
668
-
669
- ```html+erb
670
- # app/views/home/index.html.erb
671
- <div><%= t('welcome') %></div>
672
- <div><%= raw t('welcome') %></div>
673
- <div><%= t('hello_html') %></div>
674
- <div><%= t('title.html') %></div>
675
- ```
676
-
677
- Interpolation escapes as needed though. For example, given:
678
-
679
- ```yaml
680
- en:
681
- welcome_html: "<b>Welcome %{username}!</b>"
682
- ```
683
-
684
- you can safely pass the username as set by the user:
685
-
686
- ```erb
687
- <%# This is safe, it is going to be escaped if needed. %>
688
- <%= t('welcome_html', username: @current_user.username) %>
689
- ```
690
-
691
- Safe strings on the other hand are interpolated verbatim.
692
-
693
- NOTE: Automatic conversion to HTML safe translate text is only available from the `translate` view helper method.
694
-
695
- ![i18n demo html safe](images/i18n/demo_html_safe.png)
696
-
697
- ### Translations for Active Record Models
698
-
699
- You can use the methods `Model.model_name.human` and `Model.human_attribute_name(attribute)` to transparently look up translations for your model and attribute names.
700
-
701
- For example when you add the following translations:
702
-
703
- ```yaml
704
- en:
705
- activerecord:
706
- models:
707
- user: Dude
708
- attributes:
709
- user:
710
- login: "Handle"
711
- # will translate User attribute "login" as "Handle"
712
- ```
713
-
714
- Then `User.model_name.human` will return "Dude" and `User.human_attribute_name("login")` will return "Handle".
715
-
716
- You can also set a plural form for model names, adding as following:
717
-
718
- ```yaml
719
- en:
720
- activerecord:
721
- models:
722
- user:
723
- one: Dude
724
- other: Dudes
725
- ```
726
-
727
- Then `User.model_name.human(count: 2)` will return "Dudes". With `count: 1` or without params will return "Dude".
728
-
729
- In the event you need to access nested attributes within a given model, you should nest these under `model/attribute` at the model level of your translation file:
730
-
731
- ```yaml
732
- en:
733
- activerecord:
734
- attributes:
735
- user/gender:
736
- female: "Female"
737
- male: "Male"
738
- ```
739
-
740
- Then `User.human_attribute_name("gender.female")` will return "Female".
741
-
742
- #### Error Message Scopes
743
-
744
- 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.
745
-
746
- This gives you quite powerful means to flexibly adjust your messages to your application's needs.
747
-
748
- Consider a User model with a validation for the name attribute like this:
749
-
750
- ```ruby
751
- class User < ActiveRecord::Base
752
- validates :name, presence: true
753
- end
754
- ```
755
-
756
- The key for the error message in this case is `:blank`. Active Record will look up this key in the namespaces:
757
-
758
- ```ruby
759
- activerecord.errors.models.[model_name].attributes.[attribute_name]
760
- activerecord.errors.models.[model_name]
761
- activerecord.errors.messages
762
- errors.attributes.[attribute_name]
763
- errors.messages
764
- ```
765
-
766
- Thus, in our example it will try the following keys in this order and return the first result:
767
-
768
- ```ruby
769
- activerecord.errors.models.user.attributes.name.blank
770
- activerecord.errors.models.user.blank
771
- activerecord.errors.messages.blank
772
- errors.attributes.name.blank
773
- errors.messages.blank
774
- ```
775
-
776
- When your models are additionally using inheritance then the messages are looked up in the inheritance chain.
777
-
778
- For example, you might have an Admin model inheriting from User:
779
-
780
- ```ruby
781
- class Admin < User
782
- validates :name, presence: true
783
- end
784
- ```
785
-
786
- Then Active Record will look for messages in this order:
787
-
788
- ```ruby
789
- activerecord.errors.models.admin.attributes.name.blank
790
- activerecord.errors.models.admin.blank
791
- activerecord.errors.models.user.attributes.name.blank
792
- activerecord.errors.models.user.blank
793
- activerecord.errors.messages.blank
794
- errors.attributes.name.blank
795
- errors.messages.blank
796
- ```
797
-
798
- 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.
799
-
800
- #### Error Message Interpolation
801
-
802
- The translated model name, translated attribute name, and value are always available for interpolation.
803
-
804
- So, for example, instead of the default error message `"cannot be blank"` you could use the attribute name like this : `"Please fill in your %{attribute}"`.
805
-
806
- * `count`, where available, can be used for pluralization if present:
807
-
808
- | validation | with option | message | interpolation |
809
- | ------------ | ------------------------- | ------------------------- | ------------- |
810
- | confirmation | - | :confirmation | attribute |
811
- | acceptance | - | :accepted | - |
812
- | presence | - | :blank | - |
813
- | absence | - | :present | - |
814
- | length | :within, :in | :too_short | count |
815
- | length | :within, :in | :too_long | count |
816
- | length | :is | :wrong_length | count |
817
- | length | :minimum | :too_short | count |
818
- | length | :maximum | :too_long | count |
819
- | uniqueness | - | :taken | - |
820
- | format | - | :invalid | - |
821
- | inclusion | - | :inclusion | - |
822
- | exclusion | - | :exclusion | - |
823
- | associated | - | :invalid | - |
824
- | numericality | - | :not_a_number | - |
825
- | numericality | :greater_than | :greater_than | count |
826
- | numericality | :greater_than_or_equal_to | :greater_than_or_equal_to | count |
827
- | numericality | :equal_to | :equal_to | count |
828
- | numericality | :less_than | :less_than | count |
829
- | numericality | :less_than_or_equal_to | :less_than_or_equal_to | count |
830
- | numericality | :other_than | :other_than | count |
831
- | numericality | :only_integer | :not_an_integer | - |
832
- | numericality | :odd | :odd | - |
833
- | numericality | :even | :even | - |
834
-
835
- #### Translations for the Active Record `error_messages_for` Helper
836
-
837
- If you are using the Active Record `error_messages_for` helper, you will want to add
838
- translations for it.
839
-
840
- Rails ships with the following translations:
841
-
842
- ```yaml
843
- en:
844
- activerecord:
845
- errors:
846
- template:
847
- header:
848
- one: "1 error prohibited this %{model} from being saved"
849
- other: "%{count} errors prohibited this %{model} from being saved"
850
- body: "There were problems with the following fields:"
851
- ```
852
-
853
- NOTE: In order to use this helper, you need to install [DynamicForm](https://github.com/joelmoss/dynamic_form)
854
- gem by adding this line to your Gemfile: `gem 'dynamic_form'`.
855
-
856
- ### Translations for Action Mailer E-Mail Subjects
857
-
858
- If you don't pass a subject to the `mail` method, Action Mailer will try to find
859
- it in your translations. The performed lookup will use the pattern
860
- `<mailer_scope>.<action_name>.subject` to construct the key.
861
-
862
- ```ruby
863
- # user_mailer.rb
864
- class UserMailer < ActionMailer::Base
865
- def welcome(user)
866
- #...
867
- end
868
- end
869
- ```
870
-
871
- ```yaml
872
- en:
873
- user_mailer:
874
- welcome:
875
- subject: "Welcome to Rails Guides!"
876
- ```
877
-
878
- To send parameters to interpolation use the `default_i18n_subject` method on the mailer.
879
-
880
- ```ruby
881
- # user_mailer.rb
882
- class UserMailer < ActionMailer::Base
883
- def welcome(user)
884
- mail(to: user.email, subject: default_i18n_subject(user: user.name))
885
- end
886
- end
887
- ```
888
-
889
- ```yaml
890
- en:
891
- user_mailer:
892
- welcome:
893
- subject: "%{user}, welcome to Rails Guides!"
894
- ```
895
-
896
- ### Overview of Other Built-In Methods that Provide I18n Support
897
-
898
- 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.
899
-
900
- #### Action View Helper Methods
901
-
902
- * `distance_of_time_in_words` translates and pluralizes its result and interpolates the number of seconds, minutes, hours, and so on. See [datetime.distance_in_words](https://github.com/rails/rails/blob/master/actionview/lib/action_view/locale/en.yml#L4) translations.
903
-
904
- * `datetime_select` and `select_month` use translated month names for populating the resulting select tag. See [date.month_names](https://github.com/rails/rails/blob/master/activesupport/lib/active_support/locale/en.yml#L15) for translations. `datetime_select` also looks up the order option from [date.order](https://github.com/rails/rails/blob/master/activesupport/lib/active_support/locale/en.yml#L18) (unless you pass the option explicitly). All date selection helpers translate the prompt using the translations in the [datetime.prompts](https://github.com/rails/rails/blob/master/actionview/lib/action_view/locale/en.yml#L39) scope if applicable.
905
-
906
- * The `number_to_currency`, `number_with_precision`, `number_to_percentage`, `number_with_delimiter`, and `number_to_human_size` helpers use the number format settings located in the [number](https://github.com/rails/rails/blob/master/activesupport/lib/active_support/locale/en.yml#L37) scope.
907
-
908
- #### Active Model Methods
909
-
910
- * `model_name.human` and `human_attribute_name` use translations for model names and attribute names if available in the [activerecord.models](https://github.com/rails/rails/blob/master/activerecord/lib/active_record/locale/en.yml#L36) scope. They also support translations for inherited class names (e.g. for use with STI) as explained above in "Error message scopes".
911
-
912
- * `ActiveModel::Errors#generate_message` (which is used by Active Model validations but may also be used manually) uses `model_name.human` 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".
913
-
914
- * `ActiveModel::Errors#full_messages` prepends the attribute name to the error message using a separator that will be looked up from [errors.format](https://github.com/rails/rails/blob/master/activemodel/lib/active_model/locale/en.yml#L4) (and which defaults to `"%{attribute} %{message}"`).
915
-
916
- #### Active Support Methods
917
-
918
- * `Array#to_sentence` uses format settings as given in the [support.array](https://github.com/rails/rails/blob/master/activesupport/lib/active_support/locale/en.yml#L33) scope.
919
-
920
- How to Store your Custom Translations
921
- -------------------------------------
922
-
923
- The Simple backend shipped with Active Support allows you to store translations in both plain Ruby and YAML format.[^2]
924
-
925
- For example a Ruby Hash providing translations can look like this:
926
-
927
- ```yaml
928
- {
929
- pt: {
930
- foo: {
931
- bar: "baz"
932
- }
933
- }
934
- }
935
- ```
936
-
937
- The equivalent YAML file would look like this:
938
-
939
- ```yaml
940
- pt:
941
- foo:
942
- bar: baz
943
- ```
944
-
945
- As you see, in both cases the top level key is the locale. `:foo` is a namespace key and `:bar` is the key for the translation "baz".
946
-
947
- Here is a "real" example from the Active Support `en.yml` translations YAML file:
948
-
949
- ```yaml
950
- en:
951
- date:
952
- formats:
953
- default: "%Y-%m-%d"
954
- short: "%b %d"
955
- long: "%B %d, %Y"
956
- ```
957
-
958
- So, all of the following equivalent lookups will return the `:short` date format `"%b %d"`:
959
-
960
- ```ruby
961
- I18n.t 'date.formats.short'
962
- I18n.t 'formats.short', scope: :date
963
- I18n.t :short, scope: 'date.formats'
964
- I18n.t :short, scope: [:date, :formats]
965
- ```
966
-
967
- 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 formats.
968
-
969
- Customize your I18n Setup
970
- -------------------------
971
-
972
- ### Using Different Backends
973
-
974
- For several reasons the Simple backend shipped with Active Support only does the "simplest thing that could possibly 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 cannot dynamically store them to any format.
975
-
976
- 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:
977
-
978
- ```ruby
979
- I18n.backend = Globalize::Backend::Static.new
980
- ```
981
-
982
- You can also use the Chain backend to chain multiple backends together. This is useful when you want to use standard translations with a Simple backend but store custom application translations in a database or other backends. For example, you could use the Active Record backend and fall back to the (default) Simple backend:
983
-
984
- ```ruby
985
- I18n.backend = I18n::Backend::Chain.new(I18n::Backend::ActiveRecord.new, I18n.backend)
986
- ```
987
-
988
- ### Using Different Exception Handlers
989
-
990
- The I18n API defines the following exceptions that will be raised by backends when the corresponding unexpected conditions occur:
991
-
992
- ```ruby
993
- MissingTranslationData # no translation was found for the requested key
994
- InvalidLocale # the locale set to I18n.locale is invalid (e.g. nil)
995
- InvalidPluralizationData # a count option was passed but the translation data is not suitable for pluralization
996
- MissingInterpolationArgument # the translation expects an interpolation argument that has not been passed
997
- ReservedInterpolationKey # the translation contains a reserved interpolation variable name (i.e. one of: scope, default)
998
- UnknownFileType # the backend does not know how to handle a file type that was added to I18n.load_path
999
- ```
1000
-
1001
- The I18n API will catch all of these exceptions when they are 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.
1002
-
1003
- The reason for this is that during development you'd usually want your views to still render even though a translation is missing.
1004
-
1005
- In other contexts you might want to change this behavior, 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 or a class with `#call` method:
1006
-
1007
- ```ruby
1008
- module I18n
1009
- class JustRaiseExceptionHandler < ExceptionHandler
1010
- def call(exception, locale, key, options)
1011
- if exception.is_a?(MissingTranslation)
1012
- raise exception.to_exception
1013
- else
1014
- super
1015
- end
1016
- end
1017
- end
1018
- end
1019
-
1020
- I18n.exception_handler = I18n::JustRaiseExceptionHandler.new
1021
- ```
1022
-
1023
- This would re-raise only the `MissingTranslationData` exception, passing all other input to the default exception handler.
1024
-
1025
- However, if you are using `I18n::Backend::Pluralization` this handler will also raise `I18n::MissingTranslationData: translation missing: en.i18n.plural.rule` exception that should normally be ignored to fall back to the default pluralization rule for English locale. To avoid this you may use additional check for translation key:
1026
-
1027
- ```ruby
1028
- if exception.is_a?(MissingTranslation) && key.to_s != 'i18n.plural.rule'
1029
- raise exception.to_exception
1030
- else
1031
- super
1032
- end
1033
- ```
1034
-
1035
- Another example where the default behavior 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`.
1036
-
1037
- To do so, the helper forces `I18n#translate` to raise exceptions no matter what exception handler is defined by setting the `:raise` option:
1038
-
1039
- ```ruby
1040
- I18n.t :foo, raise: true # always re-raises exceptions from the backend
1041
- ```
1042
-
1043
- Conclusion
1044
- ----------
1045
-
1046
- At this point you should have a good overview about how I18n support in Ruby on Rails works and are ready to start translating your project.
1047
-
1048
- If you find anything missing or wrong in this guide, please file a ticket on our [issue tracker](http://i18n.lighthouseapp.com/projects/14948-rails-i18n/overview). If you want to discuss certain portions or have questions, please sign up to our [mailing list](http://groups.google.com/group/rails-i18n).
1049
-
1050
-
1051
- Contributing to Rails I18n
1052
- --------------------------
1053
-
1054
- 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 gems and real applications first, and only then cherry-picking the best-of-breed of most widely useful features for inclusion in the core.
1055
-
1056
- Thus we encourage everybody to experiment with new ideas and features in gems or other libraries and make them available to the community. (Don't forget to announce your work on our [mailing list](http://groups.google.com/group/rails-i18n!))
1057
-
1058
- If you find your own locale (language) missing from our [example translations data](https://github.com/svenfuchs/rails-i18n/tree/master/rails/locale) repository for Ruby on Rails, please [_fork_](https://github.com/guides/fork-a-project-and-submit-your-modifications) the repository, add your data and send a [pull request](https://github.com/guides/pull-requests).
1059
-
1060
-
1061
- Resources
1062
- ---------
1063
-
1064
- * [Google group: rails-i18n](http://groups.google.com/group/rails-i18n) - The project's mailing list.
1065
- * [GitHub: rails-i18n](https://github.com/svenfuchs/rails-i18n/tree/master) - Code repository for the rails-i18n project. Most importantly you can find lots of [example translations](https://github.com/svenfuchs/rails-i18n/tree/master/rails/locale) for Rails that should work for your application in most cases.
1066
- * [GitHub: i18n](https://github.com/svenfuchs/i18n/tree/master) - Code repository for the i18n gem.
1067
- * [Lighthouse: rails-i18n](http://i18n.lighthouseapp.com/projects/14948-rails-i18n/overview) - Issue tracker for the rails-i18n project.
1068
- * [Lighthouse: i18n](http://i18n.lighthouseapp.com/projects/14947-ruby-i18n/overview) - Issue tracker for the i18n gem.
1069
-
1070
-
1071
- Authors
1072
- -------
1073
-
1074
- * [Sven Fuchs](http://www.workingwithrails.com/person/9963-sven-fuchs) (initial author)
1075
- * [Karel Minařík](http://www.workingwithrails.com/person/7476-karel-mina-k)
1076
-
1077
- If you found this guide useful, please consider recommending its authors on [workingwithrails](http://www.workingwithrails.com).
1078
-
1079
-
1080
- Footnotes
1081
- ---------
1082
-
1083
- [^1]: Or, to quote [Wikipedia](http://en.wikipedia.org/wiki/Internationalization_and_localization): _"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."_
1084
-
1085
- [^2]: Other backends might allow or require to use other formats, e.g. a GetText backend might allow to read GetText files.
1086
-
1087
- [^3]: One of these reasons is that we don't want to imply 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.