rails 3.2.22.5 → 4.0.0.beta1

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 (281) hide show
  1. checksums.yaml +4 -4
  2. data/README.rdoc +77 -0
  3. data/guides/CHANGELOG.md +9 -0
  4. data/guides/Rakefile +77 -0
  5. data/guides/assets/images/belongs_to.png +0 -0
  6. data/guides/assets/images/book_icon.gif +0 -0
  7. data/guides/assets/images/bullet.gif +0 -0
  8. data/guides/assets/images/challenge.png +0 -0
  9. data/guides/assets/images/chapters_icon.gif +0 -0
  10. data/guides/assets/images/check_bullet.gif +0 -0
  11. data/guides/assets/images/credits_pic_blank.gif +0 -0
  12. data/guides/assets/images/csrf.png +0 -0
  13. data/guides/assets/images/edge_badge.png +0 -0
  14. data/guides/assets/images/favicon.ico +0 -0
  15. data/guides/assets/images/feature_tile.gif +0 -0
  16. data/guides/assets/images/footer_tile.gif +0 -0
  17. data/guides/assets/images/fxn.png +0 -0
  18. data/guides/assets/images/getting_started/confirm_dialog.png +0 -0
  19. data/guides/assets/images/getting_started/forbidden_attributes_for_new_post.png +0 -0
  20. data/guides/assets/images/getting_started/form_with_errors.png +0 -0
  21. data/guides/assets/images/getting_started/index_action_with_edit_link.png +0 -0
  22. data/guides/assets/images/getting_started/new_post.png +0 -0
  23. data/guides/assets/images/getting_started/post_with_comments.png +0 -0
  24. data/guides/assets/images/getting_started/routing_error_no_controller.png +0 -0
  25. data/guides/assets/images/getting_started/routing_error_no_route_matches.png +0 -0
  26. data/guides/assets/images/getting_started/show_action_for_posts.png +0 -0
  27. data/guides/assets/images/getting_started/template_is_missing_posts_new.png +0 -0
  28. data/guides/assets/images/getting_started/undefined_method_post_path.png +0 -0
  29. data/guides/assets/images/getting_started/unknown_action_create_for_posts.png +0 -0
  30. data/guides/assets/images/getting_started/unknown_action_new_for_posts.png +0 -0
  31. data/guides/assets/images/grey_bullet.gif +0 -0
  32. data/guides/assets/images/habtm.png +0 -0
  33. data/guides/assets/images/has_many.png +0 -0
  34. data/guides/assets/images/has_many_through.png +0 -0
  35. data/guides/assets/images/has_one.png +0 -0
  36. data/guides/assets/images/has_one_through.png +0 -0
  37. data/guides/assets/images/header_backdrop.png +0 -0
  38. data/guides/assets/images/header_tile.gif +0 -0
  39. data/guides/assets/images/i18n/demo_html_safe.png +0 -0
  40. data/guides/assets/images/i18n/demo_localized_pirate.png +0 -0
  41. data/guides/assets/images/i18n/demo_translated_en.png +0 -0
  42. data/guides/assets/images/i18n/demo_translated_pirate.png +0 -0
  43. data/guides/assets/images/i18n/demo_translation_missing.png +0 -0
  44. data/guides/assets/images/i18n/demo_untranslated.png +0 -0
  45. data/guides/assets/images/icons/README +5 -0
  46. data/guides/assets/images/icons/callouts/1.png +0 -0
  47. data/guides/assets/images/icons/callouts/10.png +0 -0
  48. data/guides/assets/images/icons/callouts/11.png +0 -0
  49. data/guides/assets/images/icons/callouts/12.png +0 -0
  50. data/guides/assets/images/icons/callouts/13.png +0 -0
  51. data/guides/assets/images/icons/callouts/14.png +0 -0
  52. data/guides/assets/images/icons/callouts/15.png +0 -0
  53. data/guides/assets/images/icons/callouts/2.png +0 -0
  54. data/guides/assets/images/icons/callouts/3.png +0 -0
  55. data/guides/assets/images/icons/callouts/4.png +0 -0
  56. data/guides/assets/images/icons/callouts/5.png +0 -0
  57. data/guides/assets/images/icons/callouts/6.png +0 -0
  58. data/guides/assets/images/icons/callouts/7.png +0 -0
  59. data/guides/assets/images/icons/callouts/8.png +0 -0
  60. data/guides/assets/images/icons/callouts/9.png +0 -0
  61. data/guides/assets/images/icons/caution.png +0 -0
  62. data/guides/assets/images/icons/example.png +0 -0
  63. data/guides/assets/images/icons/home.png +0 -0
  64. data/guides/assets/images/icons/important.png +0 -0
  65. data/guides/assets/images/icons/next.png +0 -0
  66. data/guides/assets/images/icons/note.png +0 -0
  67. data/guides/assets/images/icons/prev.png +0 -0
  68. data/guides/assets/images/icons/tip.png +0 -0
  69. data/guides/assets/images/icons/up.png +0 -0
  70. data/guides/assets/images/icons/warning.png +0 -0
  71. data/guides/assets/images/jaimeiniesta.jpg +0 -0
  72. data/guides/assets/images/nav_arrow.gif +0 -0
  73. data/guides/assets/images/oscardelben.jpg +0 -0
  74. data/guides/assets/images/polymorphic.png +0 -0
  75. data/guides/assets/images/radar.png +0 -0
  76. data/guides/assets/images/rails4_features.png +0 -0
  77. data/guides/assets/images/rails_guides_kindle_cover.jpg +0 -0
  78. data/guides/assets/images/rails_guides_logo.gif +0 -0
  79. data/guides/assets/images/rails_logo_remix.gif +0 -0
  80. data/guides/assets/images/rails_welcome.png +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 +57 -0
  90. data/guides/assets/javascripts/jquery.min.js +4 -0
  91. data/guides/assets/javascripts/responsive-tables.js +43 -0
  92. data/guides/assets/javascripts/syntaxhighlighter/shBrushAS3.js +59 -0
  93. data/guides/assets/javascripts/syntaxhighlighter/shBrushAppleScript.js +75 -0
  94. data/guides/assets/javascripts/syntaxhighlighter/shBrushBash.js +59 -0
  95. data/guides/assets/javascripts/syntaxhighlighter/shBrushCSharp.js +65 -0
  96. data/guides/assets/javascripts/syntaxhighlighter/shBrushColdFusion.js +100 -0
  97. data/guides/assets/javascripts/syntaxhighlighter/shBrushCpp.js +97 -0
  98. data/guides/assets/javascripts/syntaxhighlighter/shBrushCss.js +91 -0
  99. data/guides/assets/javascripts/syntaxhighlighter/shBrushDelphi.js +55 -0
  100. data/guides/assets/javascripts/syntaxhighlighter/shBrushDiff.js +41 -0
  101. data/guides/assets/javascripts/syntaxhighlighter/shBrushErlang.js +52 -0
  102. data/guides/assets/javascripts/syntaxhighlighter/shBrushGroovy.js +67 -0
  103. data/guides/assets/javascripts/syntaxhighlighter/shBrushJScript.js +52 -0
  104. data/guides/assets/javascripts/syntaxhighlighter/shBrushJava.js +57 -0
  105. data/guides/assets/javascripts/syntaxhighlighter/shBrushJavaFX.js +58 -0
  106. data/guides/assets/javascripts/syntaxhighlighter/shBrushPerl.js +72 -0
  107. data/guides/assets/javascripts/syntaxhighlighter/shBrushPhp.js +88 -0
  108. data/guides/assets/javascripts/syntaxhighlighter/shBrushPlain.js +33 -0
  109. data/guides/assets/javascripts/syntaxhighlighter/shBrushPowerShell.js +74 -0
  110. data/guides/assets/javascripts/syntaxhighlighter/shBrushPython.js +64 -0
  111. data/guides/assets/javascripts/syntaxhighlighter/shBrushRuby.js +55 -0
  112. data/guides/assets/javascripts/syntaxhighlighter/shBrushSass.js +94 -0
  113. data/guides/assets/javascripts/syntaxhighlighter/shBrushScala.js +51 -0
  114. data/guides/assets/javascripts/syntaxhighlighter/shBrushSql.js +66 -0
  115. data/guides/assets/javascripts/syntaxhighlighter/shBrushVb.js +56 -0
  116. data/guides/assets/javascripts/syntaxhighlighter/shBrushXml.js +69 -0
  117. data/guides/assets/javascripts/syntaxhighlighter/shCore.js +17 -0
  118. data/guides/assets/stylesheets/fixes.css +16 -0
  119. data/guides/assets/stylesheets/kindle.css +11 -0
  120. data/guides/assets/stylesheets/main.css +709 -0
  121. data/guides/assets/stylesheets/print.css +52 -0
  122. data/guides/assets/stylesheets/reset.css +43 -0
  123. data/guides/assets/stylesheets/responsive-tables.css +50 -0
  124. data/guides/assets/stylesheets/style.css +13 -0
  125. data/guides/assets/stylesheets/syntaxhighlighter/shCore.css +226 -0
  126. data/guides/assets/stylesheets/syntaxhighlighter/shCoreDefault.css +328 -0
  127. data/guides/assets/stylesheets/syntaxhighlighter/shCoreDjango.css +331 -0
  128. data/guides/assets/stylesheets/syntaxhighlighter/shCoreEclipse.css +339 -0
  129. data/guides/assets/stylesheets/syntaxhighlighter/shCoreEmacs.css +324 -0
  130. data/guides/assets/stylesheets/syntaxhighlighter/shCoreFadeToGrey.css +328 -0
  131. data/guides/assets/stylesheets/syntaxhighlighter/shCoreMDUltra.css +324 -0
  132. data/guides/assets/stylesheets/syntaxhighlighter/shCoreMidnight.css +324 -0
  133. data/guides/assets/stylesheets/syntaxhighlighter/shCoreRDark.css +324 -0
  134. data/guides/assets/stylesheets/syntaxhighlighter/shThemeDefault.css +117 -0
  135. data/guides/assets/stylesheets/syntaxhighlighter/shThemeDjango.css +120 -0
  136. data/guides/assets/stylesheets/syntaxhighlighter/shThemeEclipse.css +128 -0
  137. data/guides/assets/stylesheets/syntaxhighlighter/shThemeEmacs.css +113 -0
  138. data/guides/assets/stylesheets/syntaxhighlighter/shThemeFadeToGrey.css +117 -0
  139. data/guides/assets/stylesheets/syntaxhighlighter/shThemeMDUltra.css +113 -0
  140. data/guides/assets/stylesheets/syntaxhighlighter/shThemeMidnight.css +113 -0
  141. data/guides/assets/stylesheets/syntaxhighlighter/shThemeRDark.css +113 -0
  142. data/guides/assets/stylesheets/syntaxhighlighter/shThemeRailsGuides.css +116 -0
  143. data/guides/code/getting_started/Gemfile +38 -0
  144. data/guides/code/getting_started/Gemfile.lock +150 -0
  145. data/guides/code/getting_started/README.rdoc +28 -0
  146. data/guides/code/getting_started/Rakefile +6 -0
  147. data/guides/code/getting_started/app/assets/images/rails.png +0 -0
  148. data/guides/code/getting_started/app/assets/javascripts/application.js +16 -0
  149. data/guides/code/getting_started/app/assets/javascripts/comments.js.coffee +3 -0
  150. data/guides/code/getting_started/app/assets/javascripts/posts.js.coffee +3 -0
  151. data/guides/code/getting_started/app/assets/javascripts/welcome.js.coffee +3 -0
  152. data/guides/code/getting_started/app/assets/stylesheets/application.css +13 -0
  153. data/guides/code/getting_started/app/assets/stylesheets/comments.css.scss +3 -0
  154. data/guides/code/getting_started/app/assets/stylesheets/posts.css.scss +3 -0
  155. data/guides/code/getting_started/app/assets/stylesheets/welcome.css.scss +3 -0
  156. data/guides/code/getting_started/app/controllers/application_controller.rb +5 -0
  157. data/guides/code/getting_started/app/controllers/comments_controller.rb +17 -0
  158. data/guides/code/getting_started/app/controllers/posts_controller.rb +47 -0
  159. data/guides/code/getting_started/app/controllers/welcome_controller.rb +4 -0
  160. data/guides/code/getting_started/app/helpers/application_helper.rb +2 -0
  161. data/guides/code/getting_started/app/helpers/comments_helper.rb +2 -0
  162. data/guides/code/getting_started/app/helpers/posts_helper.rb +2 -0
  163. data/guides/code/getting_started/app/helpers/welcome_helper.rb +2 -0
  164. data/guides/code/getting_started/app/models/comment.rb +3 -0
  165. data/guides/code/getting_started/app/models/post.rb +7 -0
  166. data/guides/code/getting_started/app/views/comments/_comment.html.erb +15 -0
  167. data/guides/code/getting_started/app/views/comments/_form.html.erb +13 -0
  168. data/guides/code/getting_started/app/views/layouts/application.html.erb +14 -0
  169. data/guides/code/getting_started/app/views/posts/_form.html.erb +27 -0
  170. data/guides/code/getting_started/app/views/posts/edit.html.erb +5 -0
  171. data/guides/code/getting_started/app/views/posts/index.html.erb +21 -0
  172. data/guides/code/getting_started/app/views/posts/new.html.erb +5 -0
  173. data/guides/code/getting_started/app/views/posts/show.html.erb +18 -0
  174. data/guides/code/getting_started/app/views/welcome/index.html.erb +3 -0
  175. data/guides/code/getting_started/bin/bundle +4 -0
  176. data/guides/code/getting_started/bin/rails +4 -0
  177. data/guides/code/getting_started/bin/rake +4 -0
  178. data/guides/code/getting_started/config.ru +4 -0
  179. data/guides/code/getting_started/config/application.rb +17 -0
  180. data/guides/code/getting_started/config/boot.rb +4 -0
  181. data/guides/code/getting_started/config/database.yml +25 -0
  182. data/guides/code/getting_started/config/environment.rb +5 -0
  183. data/guides/code/getting_started/config/environments/development.rb +30 -0
  184. data/guides/code/getting_started/config/environments/production.rb +80 -0
  185. data/guides/code/getting_started/config/environments/test.rb +36 -0
  186. data/guides/code/getting_started/config/initializers/backtrace_silencers.rb +7 -0
  187. data/guides/code/getting_started/config/initializers/filter_parameter_logging.rb +4 -0
  188. data/guides/code/getting_started/config/initializers/inflections.rb +16 -0
  189. data/guides/code/getting_started/config/initializers/locale.rb +9 -0
  190. data/guides/code/getting_started/config/initializers/mime_types.rb +5 -0
  191. data/guides/code/getting_started/config/initializers/secret_token.rb +12 -0
  192. data/guides/code/getting_started/config/initializers/session_store.rb +3 -0
  193. data/guides/code/getting_started/config/initializers/wrap_parameters.rb +14 -0
  194. data/guides/code/getting_started/config/locales/en.yml +23 -0
  195. data/guides/code/getting_started/config/routes.rb +7 -0
  196. data/guides/code/getting_started/db/migrate/20130122042648_create_posts.rb +10 -0
  197. data/guides/code/getting_started/db/migrate/20130122045842_create_comments.rb +11 -0
  198. data/guides/code/getting_started/db/schema.rb +33 -0
  199. data/guides/code/getting_started/db/seeds.rb +7 -0
  200. data/guides/code/getting_started/public/404.html +27 -0
  201. data/guides/code/getting_started/public/422.html +26 -0
  202. data/guides/code/getting_started/public/500.html +26 -0
  203. data/guides/code/getting_started/public/favicon.ico +0 -0
  204. data/guides/code/getting_started/public/robots.txt +5 -0
  205. data/guides/code/getting_started/test/controllers/comments_controller_test.rb +7 -0
  206. data/guides/code/getting_started/test/controllers/posts_controller_test.rb +7 -0
  207. data/guides/code/getting_started/test/controllers/welcome_controller_test.rb +9 -0
  208. data/guides/code/getting_started/test/fixtures/comments.yml +11 -0
  209. data/guides/code/getting_started/test/fixtures/posts.yml +9 -0
  210. data/guides/code/getting_started/test/helpers/comments_helper_test.rb +4 -0
  211. data/guides/code/getting_started/test/helpers/posts_helper_test.rb +4 -0
  212. data/guides/code/getting_started/test/helpers/welcome_helper_test.rb +4 -0
  213. data/guides/code/getting_started/test/models/comment_test.rb +7 -0
  214. data/guides/code/getting_started/test/models/post_test.rb +7 -0
  215. data/guides/code/getting_started/test/test_helper.rb +15 -0
  216. data/guides/rails_guides.rb +44 -0
  217. data/guides/rails_guides/generator.rb +248 -0
  218. data/guides/rails_guides/helpers.rb +51 -0
  219. data/guides/rails_guides/indexer.rb +68 -0
  220. data/guides/rails_guides/kindle.rb +119 -0
  221. data/guides/rails_guides/levenshtein.rb +31 -0
  222. data/guides/rails_guides/markdown.rb +163 -0
  223. data/guides/rails_guides/markdown/renderer.rb +82 -0
  224. data/guides/source/2_2_release_notes.md +435 -0
  225. data/guides/source/2_3_release_notes.md +621 -0
  226. data/guides/source/3_0_release_notes.md +614 -0
  227. data/guides/source/3_1_release_notes.md +556 -0
  228. data/guides/source/3_2_release_notes.md +565 -0
  229. data/guides/source/4_0_release_notes.md +228 -0
  230. data/guides/source/_license.html.erb +2 -0
  231. data/guides/source/_welcome.html.erb +19 -0
  232. data/guides/source/action_controller_overview.md +872 -0
  233. data/guides/source/action_mailer_basics.md +599 -0
  234. data/guides/source/action_view_overview.md +1565 -0
  235. data/guides/source/active_model_basics.md +200 -0
  236. data/guides/source/active_record_basics.md +370 -0
  237. data/guides/source/active_record_callbacks.md +358 -0
  238. data/guides/source/active_record_querying.md +1621 -0
  239. data/guides/source/active_record_validations.md +1128 -0
  240. data/guides/source/active_support_core_extensions.md +3791 -0
  241. data/guides/source/active_support_instrumentation.md +487 -0
  242. data/guides/source/api_documentation_guidelines.md +209 -0
  243. data/guides/source/asset_pipeline.md +832 -0
  244. data/guides/source/association_basics.md +2129 -0
  245. data/guides/source/caching_with_rails.md +350 -0
  246. data/guides/source/command_line.md +594 -0
  247. data/guides/source/configuring.md +736 -0
  248. data/guides/source/contributing_to_ruby_on_rails.md +455 -0
  249. data/guides/source/credits.html.erb +76 -0
  250. data/guides/source/debugging_rails_applications.md +675 -0
  251. data/guides/source/development_dependencies_install.md +195 -0
  252. data/guides/source/documents.yaml +179 -0
  253. data/guides/source/engines.md +961 -0
  254. data/guides/source/form_helpers.md +955 -0
  255. data/guides/source/generators.md +644 -0
  256. data/guides/source/getting_started.md +1775 -0
  257. data/guides/source/i18n.md +983 -0
  258. data/guides/source/index.html.erb +27 -0
  259. data/guides/source/initialization.md +562 -0
  260. data/guides/source/kindle/KINDLE.md +26 -0
  261. data/guides/source/kindle/copyright.html.erb +1 -0
  262. data/guides/source/kindle/layout.html.erb +27 -0
  263. data/guides/source/kindle/rails_guides.opf.erb +52 -0
  264. data/guides/source/kindle/toc.html.erb +24 -0
  265. data/guides/source/kindle/toc.ncx.erb +64 -0
  266. data/guides/source/kindle/welcome.html.erb +5 -0
  267. data/guides/source/layout.html.erb +148 -0
  268. data/guides/source/layouts_and_rendering.md +1132 -0
  269. data/guides/source/migrations.md +1059 -0
  270. data/guides/source/nested_model_forms.md +225 -0
  271. data/guides/source/plugins.md +435 -0
  272. data/guides/source/rails_application_templates.md +229 -0
  273. data/guides/source/rails_on_rack.md +342 -0
  274. data/guides/source/routing.md +1088 -0
  275. data/guides/source/ruby_on_rails_guides_guidelines.md +124 -0
  276. data/guides/source/security.md +973 -0
  277. data/guides/source/testing.md +981 -0
  278. data/guides/source/upgrading_ruby_on_rails.md +286 -0
  279. data/guides/source/working_with_javascript_in_rails.md +396 -0
  280. data/guides/w3c_validator.rb +95 -0
  281. metadata +315 -31
@@ -0,0 +1,983 @@
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
+ --------------------------------------------------------------------------------
25
+
26
+ NOTE: The Ruby I18n framework provides you with all necessary means for internationalization/localization of your Rails application. You may, however, use any of various plugins and extensions available, which add additional functionality or features. See the Rails [I18n Wiki](http://rails-i18n.org/wiki) for more information.
27
+
28
+ How I18n in Ruby on Rails Works
29
+ -------------------------------
30
+
31
+ 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:
32
+
33
+ * providing support for English and similar languages out of the box
34
+ * making it easy to customize and extend everything for other languages
35
+
36
+ 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.
37
+
38
+ ### The Overall Architecture of the Library
39
+
40
+ Thus, the Ruby I18n gem is split into two parts:
41
+
42
+ * The public API of the i18n framework — a Ruby module with public methods that define how the library works
43
+ * A default backend (which is intentionally named _Simple_ backend) that implements these methods
44
+
45
+ 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.
46
+
47
+ 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.
48
+
49
+ ### The Public I18n API
50
+
51
+ The most important methods of the I18n API are:
52
+
53
+ ```ruby
54
+ translate # Lookup text translations
55
+ localize # Localize Date and Time objects to local formats
56
+ ```
57
+
58
+ These have the aliases #t and #l so you can use them like this:
59
+
60
+ ```ruby
61
+ I18n.t 'store.title'
62
+ I18n.l Time.now
63
+ ```
64
+
65
+ There are also attribute readers and writers for the following attributes:
66
+
67
+ ```ruby
68
+ load_path # Announce your custom translation files
69
+ locale # Get and set the current locale
70
+ default_locale # Get and set the default locale
71
+ exception_handler # Use a different exception_handler
72
+ backend # Use a different backend
73
+ ```
74
+
75
+ So, let's internationalize a simple Rails application from the ground up in the next chapters!
76
+
77
+ Setup the Rails Application for Internationalization
78
+ ----------------------------------------------------
79
+
80
+ There are just a few simple steps to get up and running with I18n support for your application.
81
+
82
+ ### Configure the I18n Module
83
+
84
+ 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.
85
+
86
+ Rails adds all `.rb` and `.yml` files from the `config/locales` directory to your **translations load path**, automatically.
87
+
88
+ The default `en.yml` locale in this directory contains a sample pair of translation strings:
89
+
90
+ ```ruby
91
+ en:
92
+ hello: "Hello world"
93
+ ```
94
+
95
+ 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 Record validation messages in the [`activerecord/lib/active_record/locale/en.yml`](https://github.com/rails/rails/blob/master/activerecord/lib/active_record/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.
96
+
97
+ 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.
98
+
99
+ 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. Various [Rails I18n plugins](http://rails-i18n.org/wiki) such as [Globalize3](https://github.com/svenfuchs/globalize3) may help you implement it.
100
+
101
+ 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.
102
+
103
+ 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.
104
+
105
+ The default `application.rb` files 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.
106
+
107
+ ```ruby
108
+ # The default locale is :en and all translations from config/locales/*.rb,yml are auto loaded.
109
+ # config.i18n.load_path += Dir[Rails.root.join('my', 'locales', '*.{rb,yml}').to_s]
110
+ # config.i18n.default_locale = :de
111
+ ```
112
+
113
+ ### Optional: Custom I18n Configuration Setup
114
+
115
+ 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.
116
+
117
+ 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:
118
+
119
+ ```ruby
120
+ # in config/initializers/locale.rb
121
+
122
+ # tell the I18n library where to find your translations
123
+ I18n.load_path += Dir[Rails.root.join('lib', 'locale', '*.{rb,yml}')]
124
+
125
+ # set default locale to something other than :en
126
+ I18n.default_locale = :pt
127
+ ```
128
+
129
+ ### Setting and Passing the Locale
130
+
131
+ 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.
132
+
133
+ 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.
134
+
135
+ WARNING: You may be tempted to store the chosen locale in a _session_ or a <em>cookie</em>, 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 [<em>RESTful</em>](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.
136
+
137
+ The _setting part_ is easy. You can set the locale in a `before_action` in the `ApplicationController` like this:
138
+
139
+ ```ruby
140
+ before_action :set_locale
141
+
142
+ def set_locale
143
+ I18n.locale = params[:locale] || I18n.default_locale
144
+ end
145
+ ```
146
+
147
+ 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.
148
+
149
+ 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.
150
+
151
+ ### Setting the Locale from the Domain Name
152
+
153
+ 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:
154
+
155
+ * The locale is an _obvious_ part of the URL.
156
+ * People intuitively grasp in which language the content will be displayed.
157
+ * It is very trivial to implement in Rails.
158
+ * Search engines seem to like that content in different languages lives at different, inter-linked domains.
159
+
160
+ You can implement it like this in your `ApplicationController`:
161
+
162
+ ```ruby
163
+ before_action :set_locale
164
+
165
+ def set_locale
166
+ I18n.locale = extract_locale_from_tld || I18n.default_locale
167
+ end
168
+
169
+ # Get locale from top-level domain or return nil if such locale is not available
170
+ # You have to put something like:
171
+ # 127.0.0.1 application.com
172
+ # 127.0.0.1 application.it
173
+ # 127.0.0.1 application.pl
174
+ # in your /etc/hosts file to try this out locally
175
+ def extract_locale_from_tld
176
+ parsed_locale = request.host.split('.').last
177
+ I18n.available_locales.include?(parsed_locale.to_sym) ? parsed_locale : nil
178
+ end
179
+ ```
180
+
181
+ We can also set the locale from the _subdomain_ in a very similar way:
182
+
183
+ ```ruby
184
+ # Get locale code from request subdomain (like http://it.application.local:3000)
185
+ # You have to put something like:
186
+ # 127.0.0.1 gr.application.local
187
+ # in your /etc/hosts file to try this out locally
188
+ def extract_locale_from_subdomain
189
+ parsed_locale = request.subdomains.first
190
+ I18n.available_locales.include?(parsed_locale.to_sym) ? parsed_locale : nil
191
+ end
192
+ ```
193
+
194
+ If your application includes a locale switching menu, you would then have something like this in it:
195
+
196
+ ```ruby
197
+ link_to("Deutsch", "#{APP_CONFIG[:deutsch_website_url]}#{request.env['REQUEST_URI']}")
198
+ ```
199
+
200
+ assuming you would set `APP_CONFIG[:deutsch_website_url]` to some value like `http://www.application.de`.
201
+
202
+ 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).
203
+
204
+ ### Setting the Locale from the URL Params
205
+
206
+ 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.
207
+
208
+ 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.
209
+
210
+ 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.
211
+
212
+ Rails contains infrastructure for "centralizing dynamic decisions about the URLs" in its [`ApplicationController#default_url_options`](http://api.rubyonrails.org/classes/ActionController/Base.html#M000515, which is useful precisely in this scenario: it enables us to set "defaults" for [`url_for`](http://api.rubyonrails.org/classes/ActionController/Base.html#M000503) and helper methods dependent on it (by implementing/overriding this method).
213
+
214
+ We can include something like this in our `ApplicationController` then:
215
+
216
+ ```ruby
217
+ # app/controllers/application_controller.rb
218
+ def default_url_options(options={})
219
+ logger.debug "default_url_options is passed options: #{options.inspect}\n"
220
+ { locale: I18n.locale }
221
+ end
222
+ ```
223
+
224
+ 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`.
225
+
226
+ 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.
227
+
228
+ 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:
229
+
230
+ ```ruby
231
+ # config/routes.rb
232
+ scope "/:locale" do
233
+ resources :books
234
+ end
235
+ ```
236
+
237
+ 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).
238
+
239
+ 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:
240
+
241
+ ```ruby
242
+ # config/routes.rb
243
+ scope "(:locale)", locale: /en|nl/ do
244
+ resources :books
245
+ end
246
+ ```
247
+
248
+ 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.
249
+
250
+ 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.)
251
+
252
+ You would probably need to map URLs like these:
253
+
254
+ ```ruby
255
+ # config/routes.rb
256
+ match '/:locale' => 'dashboard#index'
257
+ ```
258
+
259
+ 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.)
260
+
261
+ NOTE: Have a look at two plugins which simplify work with routes in this way: Sven Fuchs's [routing_filter](https://github.com/svenfuchs/routing-filter/tree/master and Raul Murciano's [translate_routes](https://github.com/raul/translate_routes/tree/master).
262
+
263
+ ### Setting the Locale from the Client Supplied Information
264
+
265
+ 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.
266
+
267
+
268
+ #### Using `Accept-Language`
269
+
270
+ 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_).
271
+
272
+ A trivial implementation of using an `Accept-Language` header would be:
273
+
274
+ ```ruby
275
+ def set_locale
276
+ logger.debug "* Accept-Language: #{request.env['HTTP_ACCEPT_LANGUAGE']}"
277
+ I18n.locale = extract_locale_from_accept_language_header
278
+ logger.debug "* Locale set to '#{I18n.locale}'"
279
+ end
280
+ private
281
+ def extract_locale_from_accept_language_header
282
+ request.env['HTTP_ACCEPT_LANGUAGE'].scan(/^[a-z]{2}/).first
283
+ end
284
+ ```
285
+
286
+ Of course, in a production environment you would need much more robust code, and could use a plugin 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).
287
+
288
+ #### Using GeoIP (or Similar) Database
289
+
290
+ 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.
291
+
292
+ #### User Profile
293
+
294
+ 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.
295
+
296
+ Internationalizing your Application
297
+ -----------------------------------
298
+
299
+ 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.
300
+
301
+ Let's _internationalize_ our application, i.e. abstract every locale-specific parts, and then _localize_ it, i.e. provide necessary translations for these abstracts.
302
+
303
+ You most probably have something like this in one of your applications:
304
+
305
+ ```ruby
306
+ # config/routes.rb
307
+ Yourapp::Application.routes.draw do
308
+ root to: "home#index"
309
+ end
310
+ ```
311
+
312
+ ```ruby
313
+ # app/controllers/home_controller.rb
314
+ class HomeController < ApplicationController
315
+ def index
316
+ flash[:notice] = "Hello Flash"
317
+ end
318
+ end
319
+ ```
320
+
321
+ ```html+erb
322
+ # app/views/home/index.html.erb
323
+ <h1>Hello World</h1>
324
+ <p><%= flash[:notice] %></p>
325
+ ```
326
+
327
+ ![rails i18n demo untranslated](images/i18n/demo_untranslated.png)
328
+
329
+ ### Adding Translations
330
+
331
+ 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:
332
+
333
+ ```ruby
334
+ # app/controllers/home_controller.rb
335
+ class HomeController < ApplicationController
336
+ def index
337
+ flash[:notice] = t(:hello_flash)
338
+ end
339
+ end
340
+ ```
341
+
342
+ ```html+erb
343
+ # app/views/home/index.html.erb
344
+ <h1><%=t :hello_world %></h1>
345
+ <p><%= flash[:notice] %></p>
346
+ ```
347
+
348
+ 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.
349
+
350
+ ![rails i18n demo translation missing](images/i18n/demo_translation_missing.png)
351
+
352
+ 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">`.
353
+
354
+ So let's add the missing translations into the dictionary files (i.e. do the "localization" part):
355
+
356
+ ```ruby
357
+ # config/locales/en.yml
358
+ en:
359
+ hello_world: Hello world!
360
+ hello_flash: Hello flash!
361
+
362
+ # config/locales/pirate.yml
363
+ pirate:
364
+ hello_world: Ahoy World
365
+ hello_flash: Ahoy Flash
366
+ ```
367
+
368
+ There you go. Because you haven't changed the default_locale, I18n will use English. Your application now shows:
369
+
370
+ ![rails i18n demo translated to English](images/i18n/demo_translated_en.png)
371
+
372
+ And when you change the URL to pass the pirate locale (`http://localhost:3000?locale=pirate`), you'll get:
373
+
374
+ ![rails i18n demo translated to pirate](images/i18n/demo_translated_pirate.png)
375
+
376
+ NOTE: You need to restart the server when you add new locale files.
377
+
378
+ 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.)
379
+
380
+ ### Passing variables to translations
381
+
382
+ You can use variables in the translation messages and pass their values from the view.
383
+
384
+ ```erb
385
+ # app/views/home/index.html.erb
386
+ <%=t 'greet_username', user: "Bill", message: "Goodbye" %>
387
+ ```
388
+
389
+ ```yaml
390
+ # config/locales/en.yml
391
+ en:
392
+ greet_username: "%{message}, %{user}!"
393
+ ```
394
+
395
+ ### Adding Date/Time Formats
396
+
397
+ 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.
398
+
399
+ ```erb
400
+ # app/views/home/index.html.erb
401
+ <h1><%=t :hello_world %></h1>
402
+ <p><%= flash[:notice] %></p
403
+ <p><%= l Time.now, format: :short %></p>
404
+ ```
405
+
406
+ And in our pirate translations file let's add a time format (it's already there in Rails' defaults for English):
407
+
408
+ ```ruby
409
+ # config/locales/pirate.yml
410
+ pirate:
411
+ time:
412
+ formats:
413
+ short: "arrrround %H'ish"
414
+ ```
415
+
416
+ So that would give you:
417
+
418
+ ![rails i18n demo localized time to pirate](images/i18n/demo_localized_pirate.png)
419
+
420
+ 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.
421
+
422
+ ### Inflection Rules For Other Locales
423
+
424
+ Rails 4.0 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.
425
+
426
+ ### Localized Views
427
+
428
+ Rails 2.3 introduces another convenient localization feature: localized views (templates). 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.)
429
+
430
+ 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.
431
+
432
+ ### Organization of Locale Files
433
+
434
+ 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.
435
+
436
+ For example, your `config/locales` directory could look like this:
437
+
438
+ ```
439
+ |-defaults
440
+ |---es.rb
441
+ |---en.rb
442
+ |-models
443
+ |---book
444
+ |-----es.rb
445
+ |-----en.rb
446
+ |-views
447
+ |---defaults
448
+ |-----es.rb
449
+ |-----en.rb
450
+ |---books
451
+ |-----es.rb
452
+ |-----en.rb
453
+ |---users
454
+ |-----es.rb
455
+ |-----en.rb
456
+ |---navigation
457
+ |-----es.rb
458
+ |-----en.rb
459
+ ```
460
+
461
+ 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.
462
+
463
+ 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:
464
+
465
+ ```ruby
466
+ # config/application.rb
467
+ config.i18n.load_path += Dir[Rails.root.join('config', 'locales', '**', '*.{rb,yml}')]
468
+
469
+ ```
470
+
471
+ Do check the [Rails i18n Wiki](http://rails-i18n.org/wiki) for list of tools available for managing translations.
472
+
473
+ Overview of the I18n API Features
474
+ ---------------------------------
475
+
476
+ 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.
477
+
478
+ Covered are features like these:
479
+
480
+ * looking up translations
481
+ * interpolating data into translations
482
+ * pluralizing translations
483
+ * using safe HTML translations
484
+ * localizing dates, numbers, currency, etc.
485
+
486
+ ### Looking up Translations
487
+
488
+ #### Basic Lookup, Scopes and Nested Keys
489
+
490
+ Translations are looked up by keys which can be both Symbols or Strings, so these calls are equivalent:
491
+
492
+ ```ruby
493
+ I18n.t :message
494
+ I18n.t 'message'
495
+ ```
496
+
497
+ 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:
498
+
499
+ ```ruby
500
+ I18n.t :record_invalid, scope: [:activerecord, :errors, :messages]
501
+ ```
502
+
503
+ This looks up the `:record_invalid` message in the Active Record error messages.
504
+
505
+ Additionally, both the key and scopes can be specified as dot-separated keys as in:
506
+
507
+ ```ruby
508
+ I18n.translate "activerecord.errors.messages.record_invalid"
509
+ ```
510
+
511
+ Thus the following calls are equivalent:
512
+
513
+ ```ruby
514
+ I18n.t 'activerecord.errors.messages.record_invalid'
515
+ I18n.t 'errors.messages.record_invalid', scope: :active_record
516
+ I18n.t :record_invalid, scope: 'activerecord.errors.messages'
517
+ I18n.t :record_invalid, scope: [:activerecord, :errors, :messages]
518
+ ```
519
+
520
+ #### Defaults
521
+
522
+ When a `:default` option is given, its value will be returned if the translation is missing:
523
+
524
+ ```ruby
525
+ I18n.t :missing, default: 'Not here'
526
+ # => 'Not here'
527
+ ```
528
+
529
+ 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.
530
+
531
+ 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:
532
+
533
+ ```ruby
534
+ I18n.t :missing, default: [:also_missing, 'Not here']
535
+ # => 'Not here'
536
+ ```
537
+
538
+ #### Bulk and Namespace Lookup
539
+
540
+ To look up multiple translations at once, an array of keys can be passed:
541
+
542
+ ```ruby
543
+ I18n.t [:odd, :even], scope: 'errors.messages'
544
+ # => ["must be odd", "must be even"]
545
+ ```
546
+
547
+ 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:
548
+
549
+ ```ruby
550
+ I18n.t 'activerecord.errors.messages'
551
+ # => {:inclusion=>"is not included in the list", :exclusion=> ... }
552
+ ```
553
+
554
+ #### "Lazy" Lookup
555
+
556
+ Rails implements a convenient way to look up the locale inside _views_. When you have the following dictionary:
557
+
558
+ ```yaml
559
+ es:
560
+ books:
561
+ index:
562
+ title: "Título"
563
+ ```
564
+
565
+ you can look up the `books.index.title` value **inside** `app/views/books/index.html.erb` template like this (note the dot):
566
+
567
+ ```erb
568
+ <%= t '.title' %>
569
+ ```
570
+
571
+ ### Interpolation
572
+
573
+ 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.
574
+
575
+ All options besides `:default` and `:scope` that are passed to `#translate` will be interpolated to the translation:
576
+
577
+ ```ruby
578
+ I18n.backend.store_translations :en, thanks: 'Thanks %{name}!'
579
+ I18n.translate :thanks, name: 'Jeremy'
580
+ # => 'Thanks Jeremy!'
581
+ ```
582
+
583
+ 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.
584
+
585
+ ### Pluralization
586
+
587
+ 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.
588
+
589
+ 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:
590
+
591
+ ```ruby
592
+ I18n.backend.store_translations :en, inbox: {
593
+ one: 'one message',
594
+ other: '%{count} messages'
595
+ }
596
+ I18n.translate :inbox, count: 2
597
+ # => '2 messages'
598
+
599
+ I18n.translate :inbox, count: 1
600
+ # => 'one message'
601
+ ```
602
+
603
+ The algorithm for pluralizations in `:en` is as simple as:
604
+
605
+ ```ruby
606
+ entry[count == 1 ? 0 : 1]
607
+ ```
608
+
609
+ I.e. the translation denoted as `:one` is regarded as singular, the other is used as plural (including the count being zero).
610
+
611
+ If the lookup for the key does not return a Hash suitable for pluralization, an `18n::InvalidPluralizationData` exception is raised.
612
+
613
+ ### Setting and Passing a Locale
614
+
615
+ 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`.
616
+
617
+ If no locale is passed, `I18n.locale` is used:
618
+
619
+ ```ruby
620
+ I18n.locale = :de
621
+ I18n.t :foo
622
+ I18n.l Time.now
623
+ ```
624
+
625
+ Explicitly passing a locale:
626
+
627
+ ```ruby
628
+ I18n.t :foo, locale: :de
629
+ I18n.l Time.now, locale: :de
630
+ ```
631
+
632
+ The `I18n.locale` defaults to `I18n.default_locale` which defaults to :`en`. The default locale can be set like this:
633
+
634
+ ```ruby
635
+ I18n.default_locale = :de
636
+ ```
637
+
638
+ ### Using Safe HTML Translations
639
+
640
+ Keys with a '_html' suffix and keys named 'html' are marked as HTML safe. Use them in views without escaping.
641
+
642
+ ```yaml
643
+ # config/locales/en.yml
644
+ en:
645
+ welcome: <b>welcome!</b>
646
+ hello_html: <b>hello!</b>
647
+ title:
648
+ html: <b>title!</b>
649
+ ```
650
+
651
+ ```html+erb
652
+ # app/views/home/index.html.erb
653
+ <div><%= t('welcome') %></div>
654
+ <div><%= raw t('welcome') %></div>
655
+ <div><%= t('hello_html') %></div>
656
+ <div><%= t('title.html') %></div>
657
+ ```
658
+
659
+ ![i18n demo html safe](images/i18n/demo_html_safe.png)
660
+
661
+ How to Store your Custom Translations
662
+ -------------------------------------
663
+
664
+ The Simple backend shipped with Active Support allows you to store translations in both plain Ruby and YAML format.[^2]
665
+
666
+ For example a Ruby Hash providing translations can look like this:
667
+
668
+ ```ruby
669
+ {
670
+ pt: {
671
+ foo: {
672
+ bar: "baz"
673
+ }
674
+ }
675
+ }
676
+ ```
677
+
678
+ The equivalent YAML file would look like this:
679
+
680
+ ```ruby
681
+ pt:
682
+ foo:
683
+ bar: baz
684
+ ```
685
+
686
+ 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".
687
+
688
+ Here is a "real" example from the Active Support `en.yml` translations YAML file:
689
+
690
+ ```ruby
691
+ en:
692
+ date:
693
+ formats:
694
+ default: "%Y-%m-%d"
695
+ short: "%b %d"
696
+ long: "%B %d, %Y"
697
+ ```
698
+
699
+ So, all of the following equivalent lookups will return the `:short` date format `"%b %d"`:
700
+
701
+ ```ruby
702
+ I18n.t 'date.formats.short'
703
+ I18n.t 'formats.short', scope: :date
704
+ I18n.t :short, scope: 'date.formats'
705
+ I18n.t :short, scope: [:date, :formats]
706
+ ```
707
+
708
+ 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.
709
+
710
+ ### Translations for Active Record Models
711
+
712
+ 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.
713
+
714
+ For example when you add the following translations:
715
+
716
+ ```ruby
717
+ en:
718
+ activerecord:
719
+ models:
720
+ user: Dude
721
+ attributes:
722
+ user:
723
+ login: "Handle"
724
+ # will translate User attribute "login" as "Handle"
725
+ ```
726
+
727
+ Then `User.model_name.human` will return "Dude" and `User.human_attribute_name("login")` will return "Handle".
728
+
729
+ #### Error Message Scopes
730
+
731
+ 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.
732
+
733
+ This gives you quite powerful means to flexibly adjust your messages to your application's needs.
734
+
735
+ Consider a User model with a validation for the name attribute like this:
736
+
737
+ ```ruby
738
+ class User < ActiveRecord::Base
739
+ validates :name, presence: true
740
+ end
741
+ ```
742
+
743
+ The key for the error message in this case is `:blank`. Active Record will look up this key in the namespaces:
744
+
745
+ ```ruby
746
+ activerecord.errors.models.[model_name].attributes.[attribute_name]
747
+ activerecord.errors.models.[model_name]
748
+ activerecord.errors.messages
749
+ errors.attributes.[attribute_name]
750
+ errors.messages
751
+ ```
752
+
753
+ Thus, in our example it will try the following keys in this order and return the first result:
754
+
755
+ ```ruby
756
+ activerecord.errors.models.user.attributes.name.blank
757
+ activerecord.errors.models.user.blank
758
+ activerecord.errors.messages.blank
759
+ errors.attributes.name.blank
760
+ errors.messages.blank
761
+ ```
762
+
763
+ When your models are additionally using inheritance then the messages are looked up in the inheritance chain.
764
+
765
+ For example, you might have an Admin model inheriting from User:
766
+
767
+ ```ruby
768
+ class Admin < User
769
+ validates :name, presence: true
770
+ end
771
+ ```
772
+
773
+ Then Active Record will look for messages in this order:
774
+
775
+ ```ruby
776
+ activerecord.errors.models.admin.attributes.name.blank
777
+ activerecord.errors.models.admin.blank
778
+ activerecord.errors.models.user.attributes.name.blank
779
+ activerecord.errors.models.user.blank
780
+ activerecord.errors.messages.blank
781
+ errors.attributes.name.blank
782
+ errors.messages.blank
783
+ ```
784
+
785
+ 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.
786
+
787
+ #### Error Message Interpolation
788
+
789
+ The translated model name, translated attribute name, and value are always available for interpolation.
790
+
791
+ 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}"`.
792
+
793
+ * `count`, where available, can be used for pluralization if present:
794
+
795
+ | validation | with option | message | interpolation |
796
+ | ------------ | ------------------------- | ------------------------- | ------------- |
797
+ | confirmation | - | :confirmation | - |
798
+ | acceptance | - | :accepted | - |
799
+ | presence | - | :blank | - |
800
+ | length | :within, :in | :too_short | count |
801
+ | length | :within, :in | :too_long | count |
802
+ | length | :is | :wrong_length | count |
803
+ | length | :minimum | :too_short | count |
804
+ | length | :maximum | :too_long | count |
805
+ | uniqueness | - | :taken | - |
806
+ | format | - | :invalid | - |
807
+ | inclusion | - | :inclusion | - |
808
+ | exclusion | - | :exclusion | - |
809
+ | associated | - | :invalid | - |
810
+ | numericality | - | :not_a_number | - |
811
+ | numericality | :greater_than | :greater_than | count |
812
+ | numericality | :greater_than_or_equal_to | :greater_than_or_equal_to | count |
813
+ | numericality | :equal_to | :equal_to | count |
814
+ | numericality | :less_than | :less_than | count |
815
+ | numericality | :less_than_or_equal_to | :less_than_or_equal_to | count |
816
+ | numericality | :odd | :odd | - |
817
+ | numericality | :even | :even | - |
818
+
819
+ #### Translations for the Active Record `error_messages_for` Helper
820
+
821
+ If you are using the Active Record `error_messages_for` helper, you will want to add
822
+ translations for it.
823
+
824
+ Rails ships with the following translations:
825
+
826
+ ```yaml
827
+ en:
828
+ activerecord:
829
+ errors:
830
+ template:
831
+ header:
832
+ one: "1 error prohibited this %{model} from being saved"
833
+ other: "%{count} errors prohibited this %{model} from being saved"
834
+ body: "There were problems with the following fields:"
835
+ ```
836
+
837
+ NOTE: In order to use this helper, you need to install [DynamicForm](https://github.com/joelmoss/dynamic_form)
838
+ gem by adding this line to your Gemfile: `gem 'dynamic_form'`.
839
+
840
+ ### Overview of Other Built-In Methods that Provide I18n Support
841
+
842
+ 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.
843
+
844
+ #### Action View Helper Methods
845
+
846
+ * `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/actionpack/lib/action_view/locale/en.yml#L51) translations.
847
+
848
+ * `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/actionpack/lib/action_view/locale/en.yml#L83) scope if applicable.
849
+
850
+ * 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/actionpack/lib/action_view/locale/en.yml#L2) scope.
851
+
852
+ #### Active Model Methods
853
+
854
+ * `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#L29) scope. They also support translations for inherited class names (e.g. for use with STI) as explained above in "Error message scopes".
855
+
856
+ * `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".
857
+
858
+ * `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}"`).
859
+
860
+ #### Active Support Methods
861
+
862
+ * `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#L30) scope.
863
+
864
+ Customize your I18n Setup
865
+ -------------------------
866
+
867
+ ### Using Different Backends
868
+
869
+ 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 can not dynamically store them to any format.
870
+
871
+ 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:
872
+
873
+ ```ruby
874
+ I18n.backend = Globalize::Backend::Static.new
875
+ ```
876
+
877
+ 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:
878
+
879
+ ```ruby
880
+ I18n.backend = I18n::Backend::Chain.new(I18n::Backend::ActiveRecord.new, I18n.backend)
881
+ ```
882
+
883
+ ### Using Different Exception Handlers
884
+
885
+ The I18n API defines the following exceptions that will be raised by backends when the corresponding unexpected conditions occur:
886
+
887
+ ```ruby
888
+ MissingTranslationData # no translation was found for the requested key
889
+ InvalidLocale # the locale set to I18n.locale is invalid (e.g. nil)
890
+ InvalidPluralizationData # a count option was passed but the translation data is not suitable for pluralization
891
+ MissingInterpolationArgument # the translation expects an interpolation argument that has not been passed
892
+ ReservedInterpolationKey # the translation contains a reserved interpolation variable name (i.e. one of: scope, default)
893
+ UnknownFileType # the backend does not know how to handle a file type that was added to I18n.load_path
894
+ ```
895
+
896
+ 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.
897
+
898
+ The reason for this is that during development you'd usually want your views to still render even though a translation is missing.
899
+
900
+ 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:
901
+
902
+ ```ruby
903
+ module I18n
904
+ class JustRaiseExceptionHandler < ExceptionHandler
905
+ def call(exception, locale, key, options)
906
+ if exception.is_a?(MissingTranslation)
907
+ raise exception.to_exception
908
+ else
909
+ super
910
+ end
911
+ end
912
+ end
913
+ end
914
+
915
+ I18n.exception_handler = I18n::JustRaiseExceptionHandler.new
916
+ ```
917
+
918
+ This would re-raise only the `MissingTranslationData` exception, passing all other input to the default exception handler.
919
+
920
+ 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:
921
+
922
+ ```ruby
923
+ if exception.is_a?(MissingTranslation) && key.to_s != 'i18n.plural.rule'
924
+ raise exception.to_exception
925
+ else
926
+ super
927
+ end
928
+ ```
929
+
930
+ 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`.
931
+
932
+ To do so, the helper forces `I18n#translate` to raise exceptions no matter what exception handler is defined by setting the `:raise` option:
933
+
934
+ ```ruby
935
+ I18n.t :foo, raise: true # always re-raises exceptions from the backend
936
+ ```
937
+
938
+ Conclusion
939
+ ----------
940
+
941
+ 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.
942
+
943
+ 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).
944
+
945
+
946
+ Contributing to Rails I18n
947
+ --------------------------
948
+
949
+ 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 only then cherry-picking the best-of-breed of most widely useful features for inclusion in the core.
950
+
951
+ 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 [mailing list](http://groups.google.com/group/rails-i18n!))
952
+
953
+ 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).
954
+
955
+
956
+ Resources
957
+ ---------
958
+
959
+ * [rails-i18n.org](http://rails-i18n.org) - Homepage of the rails-i18n project. You can find lots of useful resources on the [wiki](http://rails-i18n.org/wiki).
960
+ * [Google group: rails-i18n](http://groups.google.com/group/rails-i18n) - The project's mailing list.
961
+ * [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.
962
+ * [Github: i18n](https://github.com/svenfuchs/i18n/tree/master) - Code repository for the i18n gem.
963
+ * [Lighthouse: rails-i18n](http://i18n.lighthouseapp.com/projects/14948-rails-i18n/overview) - Issue tracker for the rails-i18n project.
964
+ * [Lighthouse: i18n](http://i18n.lighthouseapp.com/projects/14947-ruby-i18n/overview) - Issue tracker for the i18n gem.
965
+
966
+
967
+ Authors
968
+ -------
969
+
970
+ * [Sven Fuchs](http://www.workingwithrails.com/person/9963-sven-fuchs) (initial author)
971
+ * [Karel Minařík](http://www.workingwithrails.com/person/7476-karel-mina-k)
972
+
973
+ If you found this guide useful, please consider recommending its authors on [workingwithrails](http://www.workingwithrails.com).
974
+
975
+
976
+ Footnotes
977
+ ---------
978
+
979
+ [^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."_
980
+
981
+ [^2]: Other backends might allow or require to use other formats, e.g. a GetText backend might allow to read GetText files.
982
+
983
+ [^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.