rails 4.1.4 → 6.0.0

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 (284) hide show
  1. checksums.yaml +5 -5
  2. data/README.md +55 -34
  3. metadata +93 -311
  4. data/guides/CHANGELOG.md +0 -41
  5. data/guides/Rakefile +0 -77
  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 -53
  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 -710
  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 -53
  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/code/getting_started/Gemfile +0 -40
  148. data/guides/code/getting_started/Gemfile.lock +0 -125
  149. data/guides/code/getting_started/README.rdoc +0 -28
  150. data/guides/code/getting_started/Rakefile +0 -6
  151. data/guides/code/getting_started/app/assets/javascripts/application.js +0 -15
  152. data/guides/code/getting_started/app/assets/javascripts/comments.js.coffee +0 -3
  153. data/guides/code/getting_started/app/assets/javascripts/posts.js.coffee +0 -3
  154. data/guides/code/getting_started/app/assets/javascripts/welcome.js.coffee +0 -3
  155. data/guides/code/getting_started/app/assets/stylesheets/application.css +0 -13
  156. data/guides/code/getting_started/app/assets/stylesheets/comments.css.scss +0 -3
  157. data/guides/code/getting_started/app/assets/stylesheets/posts.css.scss +0 -3
  158. data/guides/code/getting_started/app/assets/stylesheets/welcome.css.scss +0 -3
  159. data/guides/code/getting_started/app/controllers/application_controller.rb +0 -5
  160. data/guides/code/getting_started/app/controllers/comments_controller.rb +0 -23
  161. data/guides/code/getting_started/app/controllers/posts_controller.rb +0 -53
  162. data/guides/code/getting_started/app/controllers/welcome_controller.rb +0 -4
  163. data/guides/code/getting_started/app/helpers/application_helper.rb +0 -2
  164. data/guides/code/getting_started/app/helpers/comments_helper.rb +0 -2
  165. data/guides/code/getting_started/app/helpers/posts_helper.rb +0 -2
  166. data/guides/code/getting_started/app/helpers/welcome_helper.rb +0 -2
  167. data/guides/code/getting_started/app/models/comment.rb +0 -3
  168. data/guides/code/getting_started/app/models/post.rb +0 -7
  169. data/guides/code/getting_started/app/views/comments/_comment.html.erb +0 -15
  170. data/guides/code/getting_started/app/views/comments/_form.html.erb +0 -13
  171. data/guides/code/getting_started/app/views/layouts/application.html.erb +0 -14
  172. data/guides/code/getting_started/app/views/posts/_form.html.erb +0 -27
  173. data/guides/code/getting_started/app/views/posts/edit.html.erb +0 -5
  174. data/guides/code/getting_started/app/views/posts/index.html.erb +0 -21
  175. data/guides/code/getting_started/app/views/posts/new.html.erb +0 -5
  176. data/guides/code/getting_started/app/views/posts/show.html.erb +0 -18
  177. data/guides/code/getting_started/app/views/welcome/index.html.erb +0 -4
  178. data/guides/code/getting_started/bin/bundle +0 -4
  179. data/guides/code/getting_started/bin/rails +0 -4
  180. data/guides/code/getting_started/bin/rake +0 -4
  181. data/guides/code/getting_started/config/application.rb +0 -18
  182. data/guides/code/getting_started/config/boot.rb +0 -4
  183. data/guides/code/getting_started/config/database.yml +0 -25
  184. data/guides/code/getting_started/config/environment.rb +0 -5
  185. data/guides/code/getting_started/config/environments/development.rb +0 -30
  186. data/guides/code/getting_started/config/environments/production.rb +0 -80
  187. data/guides/code/getting_started/config/environments/test.rb +0 -36
  188. data/guides/code/getting_started/config/initializers/backtrace_silencers.rb +0 -7
  189. data/guides/code/getting_started/config/initializers/filter_parameter_logging.rb +0 -4
  190. data/guides/code/getting_started/config/initializers/inflections.rb +0 -16
  191. data/guides/code/getting_started/config/initializers/locale.rb +0 -9
  192. data/guides/code/getting_started/config/initializers/mime_types.rb +0 -5
  193. data/guides/code/getting_started/config/initializers/secret_token.rb +0 -12
  194. data/guides/code/getting_started/config/initializers/session_store.rb +0 -3
  195. data/guides/code/getting_started/config/initializers/wrap_parameters.rb +0 -14
  196. data/guides/code/getting_started/config/locales/en.yml +0 -23
  197. data/guides/code/getting_started/config/routes.rb +0 -7
  198. data/guides/code/getting_started/config.ru +0 -4
  199. data/guides/code/getting_started/db/migrate/20130122042648_create_posts.rb +0 -10
  200. data/guides/code/getting_started/db/migrate/20130122045842_create_comments.rb +0 -11
  201. data/guides/code/getting_started/db/schema.rb +0 -33
  202. data/guides/code/getting_started/db/seeds.rb +0 -7
  203. data/guides/code/getting_started/public/404.html +0 -60
  204. data/guides/code/getting_started/public/422.html +0 -60
  205. data/guides/code/getting_started/public/500.html +0 -59
  206. data/guides/code/getting_started/public/favicon.ico +0 -0
  207. data/guides/code/getting_started/public/robots.txt +0 -5
  208. data/guides/code/getting_started/test/controllers/comments_controller_test.rb +0 -7
  209. data/guides/code/getting_started/test/controllers/posts_controller_test.rb +0 -7
  210. data/guides/code/getting_started/test/controllers/welcome_controller_test.rb +0 -9
  211. data/guides/code/getting_started/test/fixtures/comments.yml +0 -11
  212. data/guides/code/getting_started/test/fixtures/posts.yml +0 -9
  213. data/guides/code/getting_started/test/helpers/comments_helper_test.rb +0 -4
  214. data/guides/code/getting_started/test/helpers/posts_helper_test.rb +0 -4
  215. data/guides/code/getting_started/test/helpers/welcome_helper_test.rb +0 -4
  216. data/guides/code/getting_started/test/models/comment_test.rb +0 -7
  217. data/guides/code/getting_started/test/models/post_test.rb +0 -7
  218. data/guides/code/getting_started/test/test_helper.rb +0 -12
  219. data/guides/rails_guides/generator.rb +0 -248
  220. data/guides/rails_guides/helpers.rb +0 -53
  221. data/guides/rails_guides/indexer.rb +0 -68
  222. data/guides/rails_guides/kindle.rb +0 -119
  223. data/guides/rails_guides/levenshtein.rb +0 -31
  224. data/guides/rails_guides/markdown/renderer.rb +0 -82
  225. data/guides/rails_guides/markdown.rb +0 -163
  226. data/guides/rails_guides.rb +0 -63
  227. data/guides/source/2_2_release_notes.md +0 -435
  228. data/guides/source/2_3_release_notes.md +0 -621
  229. data/guides/source/3_0_release_notes.md +0 -611
  230. data/guides/source/3_1_release_notes.md +0 -556
  231. data/guides/source/3_2_release_notes.md +0 -565
  232. data/guides/source/4_0_release_notes.md +0 -276
  233. data/guides/source/4_1_release_notes.md +0 -731
  234. data/guides/source/_license.html.erb +0 -2
  235. data/guides/source/_welcome.html.erb +0 -25
  236. data/guides/source/action_controller_overview.md +0 -1175
  237. data/guides/source/action_mailer_basics.md +0 -689
  238. data/guides/source/action_view_overview.md +0 -1610
  239. data/guides/source/active_model_basics.md +0 -200
  240. data/guides/source/active_record_basics.md +0 -373
  241. data/guides/source/active_record_callbacks.md +0 -410
  242. data/guides/source/active_record_querying.md +0 -1773
  243. data/guides/source/active_record_validations.md +0 -1169
  244. data/guides/source/active_support_core_extensions.md +0 -3864
  245. data/guides/source/active_support_instrumentation.md +0 -496
  246. data/guides/source/api_documentation_guidelines.md +0 -315
  247. data/guides/source/asset_pipeline.md +0 -1163
  248. data/guides/source/association_basics.md +0 -2229
  249. data/guides/source/caching_with_rails.md +0 -354
  250. data/guides/source/command_line.md +0 -603
  251. data/guides/source/configuring.md +0 -942
  252. data/guides/source/contributing_to_ruby_on_rails.md +0 -544
  253. data/guides/source/credits.html.erb +0 -80
  254. data/guides/source/debugging_rails_applications.md +0 -707
  255. data/guides/source/development_dependencies_install.md +0 -278
  256. data/guides/source/documents.yaml +0 -193
  257. data/guides/source/engines.md +0 -1391
  258. data/guides/source/form_helpers.md +0 -1001
  259. data/guides/source/generators.md +0 -663
  260. data/guides/source/getting_started.md +0 -1947
  261. data/guides/source/i18n.md +0 -1043
  262. data/guides/source/index.html.erb +0 -27
  263. data/guides/source/initialization.md +0 -657
  264. data/guides/source/kindle/copyright.html.erb +0 -1
  265. data/guides/source/kindle/layout.html.erb +0 -27
  266. data/guides/source/kindle/rails_guides.opf.erb +0 -52
  267. data/guides/source/kindle/toc.html.erb +0 -24
  268. data/guides/source/kindle/toc.ncx.erb +0 -64
  269. data/guides/source/kindle/welcome.html.erb +0 -5
  270. data/guides/source/layout.html.erb +0 -146
  271. data/guides/source/layouts_and_rendering.md +0 -1226
  272. data/guides/source/maintenance_policy.md +0 -56
  273. data/guides/source/migrations.md +0 -1109
  274. data/guides/source/nested_model_forms.md +0 -225
  275. data/guides/source/plugins.md +0 -444
  276. data/guides/source/rails_application_templates.md +0 -248
  277. data/guides/source/rails_on_rack.md +0 -333
  278. data/guides/source/routing.md +0 -1115
  279. data/guides/source/ruby_on_rails_guides_guidelines.md +0 -128
  280. data/guides/source/security.md +0 -1018
  281. data/guides/source/testing.md +0 -1052
  282. data/guides/source/upgrading_ruby_on_rails.md +0 -899
  283. data/guides/source/working_with_javascript_in_rails.md +0 -405
  284. data/guides/w3c_validator.rb +0 -95
@@ -1,1043 +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, however, use any of various plugins and extensions available, which add additional functionality or features. See the Ruby [I18n Wiki](http://ruby-i18n.org/wiki) 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
- ```ruby
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. Various [Rails I18n plugins](http://rails-i18n.org/wiki) 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` 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.
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 <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.
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/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).
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
- logger.debug "default_url_options is passed options: #{options.inspect}\n"
225
- { locale: I18n.locale }
226
- end
227
- ```
228
-
229
- 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`.
230
-
231
- 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.
232
-
233
- 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:
234
-
235
- ```ruby
236
- # config/routes.rb
237
- scope "/:locale" do
238
- resources :books
239
- end
240
- ```
241
-
242
- 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).
243
-
244
- 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:
245
-
246
- ```ruby
247
- # config/routes.rb
248
- scope "(:locale)", locale: /en|nl/ do
249
- resources :books
250
- end
251
- ```
252
-
253
- 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.
254
-
255
- 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.)
256
-
257
- You would probably need to map URLs like these:
258
-
259
- ```ruby
260
- # config/routes.rb
261
- get '/:locale' => 'dashboard#index'
262
- ```
263
-
264
- 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.)
265
-
266
- 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).
267
-
268
- ### Setting the Locale from the Client Supplied Information
269
-
270
- 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.
271
-
272
-
273
- #### Using `Accept-Language`
274
-
275
- 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_).
276
-
277
- A trivial implementation of using an `Accept-Language` header would be:
278
-
279
- ```ruby
280
- def set_locale
281
- logger.debug "* Accept-Language: #{request.env['HTTP_ACCEPT_LANGUAGE']}"
282
- I18n.locale = extract_locale_from_accept_language_header
283
- logger.debug "* Locale set to '#{I18n.locale}'"
284
- end
285
-
286
- private
287
- def extract_locale_from_accept_language_header
288
- request.env['HTTP_ACCEPT_LANGUAGE'].scan(/^[a-z]{2}/).first
289
- end
290
- ```
291
-
292
- 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).
293
-
294
- #### Using GeoIP (or Similar) Database
295
-
296
- 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.
297
-
298
- #### User Profile
299
-
300
- 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.
301
-
302
- Internationalizing your Application
303
- -----------------------------------
304
-
305
- 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.
306
-
307
- Let's _internationalize_ our application, i.e. abstract every locale-specific parts, and then _localize_ it, i.e. provide necessary translations for these abstracts.
308
-
309
- You most probably have something like this in one of your applications:
310
-
311
- ```ruby
312
- # config/routes.rb
313
- Yourapp::Application.routes.draw do
314
- root to: "home#index"
315
- end
316
- ```
317
-
318
- ```ruby
319
- # app/controllers/application_controller.rb
320
- class ApplicationController < ActionController::Base
321
- before_action :set_locale
322
-
323
- def set_locale
324
- I18n.locale = params[:locale] || I18n.default_locale
325
- end
326
- end
327
- ```
328
-
329
- ```ruby
330
- # app/controllers/home_controller.rb
331
- class HomeController < ApplicationController
332
- def index
333
- flash[:notice] = "Hello Flash"
334
- end
335
- end
336
- ```
337
-
338
- ```html+erb
339
- # app/views/home/index.html.erb
340
- <h1>Hello World</h1>
341
- <p><%= flash[:notice] %></p>
342
- ```
343
-
344
- ![rails i18n demo untranslated](images/i18n/demo_untranslated.png)
345
-
346
- ### Adding Translations
347
-
348
- 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:
349
-
350
- ```ruby
351
- # app/controllers/home_controller.rb
352
- class HomeController < ApplicationController
353
- def index
354
- flash[:notice] = t(:hello_flash)
355
- end
356
- end
357
- ```
358
-
359
- ```html+erb
360
- # app/views/home/index.html.erb
361
- <h1><%=t :hello_world %></h1>
362
- <p><%= flash[:notice] %></p>
363
- ```
364
-
365
- 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.
366
-
367
- ![rails i18n demo translation missing](images/i18n/demo_translation_missing.png)
368
-
369
- 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">`.
370
-
371
- So let's add the missing translations into the dictionary files (i.e. do the "localization" part):
372
-
373
- ```ruby
374
- # config/locales/en.yml
375
- en:
376
- hello_world: Hello world!
377
- hello_flash: Hello flash!
378
-
379
- # config/locales/pirate.yml
380
- pirate:
381
- hello_world: Ahoy World
382
- hello_flash: Ahoy Flash
383
- ```
384
-
385
- There you go. Because you haven't changed the default_locale, I18n will use English. Your application now shows:
386
-
387
- ![rails i18n demo translated to English](images/i18n/demo_translated_en.png)
388
-
389
- And when you change the URL to pass the pirate locale (`http://localhost:3000?locale=pirate`), you'll get:
390
-
391
- ![rails i18n demo translated to pirate](images/i18n/demo_translated_pirate.png)
392
-
393
- NOTE: You need to restart the server when you add new locale files.
394
-
395
- 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.)
396
-
397
- ### Passing variables to translations
398
-
399
- You can use variables in the translation messages and pass their values from the view.
400
-
401
- ```erb
402
- # app/views/home/index.html.erb
403
- <%=t 'greet_username', user: "Bill", message: "Goodbye" %>
404
- ```
405
-
406
- ```yaml
407
- # config/locales/en.yml
408
- en:
409
- greet_username: "%{message}, %{user}!"
410
- ```
411
-
412
- ### Adding Date/Time Formats
413
-
414
- 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.
415
-
416
- ```erb
417
- # app/views/home/index.html.erb
418
- <h1><%=t :hello_world %></h1>
419
- <p><%= flash[:notice] %></p
420
- <p><%= l Time.now, format: :short %></p>
421
- ```
422
-
423
- And in our pirate translations file let's add a time format (it's already there in Rails' defaults for English):
424
-
425
- ```ruby
426
- # config/locales/pirate.yml
427
- pirate:
428
- time:
429
- formats:
430
- short: "arrrround %H'ish"
431
- ```
432
-
433
- So that would give you:
434
-
435
- ![rails i18n demo localized time to pirate](images/i18n/demo_localized_pirate.png)
436
-
437
- 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.
438
-
439
- ### Inflection Rules For Other Locales
440
-
441
- 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.
442
-
443
- ### Localized Views
444
-
445
- 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.)
446
-
447
- 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.
448
-
449
- ### Organization of Locale Files
450
-
451
- 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.
452
-
453
- For example, your `config/locales` directory could look like this:
454
-
455
- ```
456
- |-defaults
457
- |---es.rb
458
- |---en.rb
459
- |-models
460
- |---book
461
- |-----es.rb
462
- |-----en.rb
463
- |-views
464
- |---defaults
465
- |-----es.rb
466
- |-----en.rb
467
- |---books
468
- |-----es.rb
469
- |-----en.rb
470
- |---users
471
- |-----es.rb
472
- |-----en.rb
473
- |---navigation
474
- |-----es.rb
475
- |-----en.rb
476
- ```
477
-
478
- 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.
479
-
480
- 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:
481
-
482
- ```ruby
483
- # config/application.rb
484
- config.i18n.load_path += Dir[Rails.root.join('config', 'locales', '**', '*.{rb,yml}')]
485
-
486
- ```
487
-
488
- Do check the [Rails i18n Wiki](http://rails-i18n.org/wiki) for list of tools available for managing translations.
489
-
490
- Overview of the I18n API Features
491
- ---------------------------------
492
-
493
- 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.
494
-
495
- 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).
496
-
497
- Covered are features like these:
498
-
499
- * looking up translations
500
- * interpolating data into translations
501
- * pluralizing translations
502
- * using safe HTML translations (view helper method only)
503
- * localizing dates, numbers, currency, etc.
504
-
505
- ### Looking up Translations
506
-
507
- #### Basic Lookup, Scopes and Nested Keys
508
-
509
- Translations are looked up by keys which can be both Symbols or Strings, so these calls are equivalent:
510
-
511
- ```ruby
512
- I18n.t :message
513
- I18n.t 'message'
514
- ```
515
-
516
- 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:
517
-
518
- ```ruby
519
- I18n.t :record_invalid, scope: [:activerecord, :errors, :messages]
520
- ```
521
-
522
- This looks up the `:record_invalid` message in the Active Record error messages.
523
-
524
- Additionally, both the key and scopes can be specified as dot-separated keys as in:
525
-
526
- ```ruby
527
- I18n.translate "activerecord.errors.messages.record_invalid"
528
- ```
529
-
530
- Thus the following calls are equivalent:
531
-
532
- ```ruby
533
- I18n.t 'activerecord.errors.messages.record_invalid'
534
- I18n.t 'errors.messages.record_invalid', scope: :active_record
535
- I18n.t :record_invalid, scope: 'activerecord.errors.messages'
536
- I18n.t :record_invalid, scope: [:activerecord, :errors, :messages]
537
- ```
538
-
539
- #### Defaults
540
-
541
- When a `:default` option is given, its value will be returned if the translation is missing:
542
-
543
- ```ruby
544
- I18n.t :missing, default: 'Not here'
545
- # => 'Not here'
546
- ```
547
-
548
- 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.
549
-
550
- 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:
551
-
552
- ```ruby
553
- I18n.t :missing, default: [:also_missing, 'Not here']
554
- # => 'Not here'
555
- ```
556
-
557
- #### Bulk and Namespace Lookup
558
-
559
- To look up multiple translations at once, an array of keys can be passed:
560
-
561
- ```ruby
562
- I18n.t [:odd, :even], scope: 'errors.messages'
563
- # => ["must be odd", "must be even"]
564
- ```
565
-
566
- 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:
567
-
568
- ```ruby
569
- I18n.t 'activerecord.errors.messages'
570
- # => {:inclusion=>"is not included in the list", :exclusion=> ... }
571
- ```
572
-
573
- #### "Lazy" Lookup
574
-
575
- Rails implements a convenient way to look up the locale inside _views_. When you have the following dictionary:
576
-
577
- ```yaml
578
- es:
579
- books:
580
- index:
581
- title: "Título"
582
- ```
583
-
584
- you can look up the `books.index.title` value **inside** `app/views/books/index.html.erb` template like this (note the dot):
585
-
586
- ```erb
587
- <%= t '.title' %>
588
- ```
589
-
590
- NOTE: Automatic translation scoping by partial is only available from the `translate` view helper method.
591
-
592
- ### Interpolation
593
-
594
- 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.
595
-
596
- All options besides `:default` and `:scope` that are passed to `#translate` will be interpolated to the translation:
597
-
598
- ```ruby
599
- I18n.backend.store_translations :en, thanks: 'Thanks %{name}!'
600
- I18n.translate :thanks, name: 'Jeremy'
601
- # => 'Thanks Jeremy!'
602
- ```
603
-
604
- 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.
605
-
606
- ### Pluralization
607
-
608
- 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.
609
-
610
- 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:
611
-
612
- ```ruby
613
- I18n.backend.store_translations :en, inbox: {
614
- one: 'one message',
615
- other: '%{count} messages'
616
- }
617
- I18n.translate :inbox, count: 2
618
- # => '2 messages'
619
-
620
- I18n.translate :inbox, count: 1
621
- # => 'one message'
622
- ```
623
-
624
- The algorithm for pluralizations in `:en` is as simple as:
625
-
626
- ```ruby
627
- entry[count == 1 ? 0 : 1]
628
- ```
629
-
630
- I.e. the translation denoted as `:one` is regarded as singular, the other is used as plural (including the count being zero).
631
-
632
- If the lookup for the key does not return a Hash suitable for pluralization, an `18n::InvalidPluralizationData` exception is raised.
633
-
634
- ### Setting and Passing a Locale
635
-
636
- 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`.
637
-
638
- If no locale is passed, `I18n.locale` is used:
639
-
640
- ```ruby
641
- I18n.locale = :de
642
- I18n.t :foo
643
- I18n.l Time.now
644
- ```
645
-
646
- Explicitly passing a locale:
647
-
648
- ```ruby
649
- I18n.t :foo, locale: :de
650
- I18n.l Time.now, locale: :de
651
- ```
652
-
653
- The `I18n.locale` defaults to `I18n.default_locale` which defaults to :`en`. The default locale can be set like this:
654
-
655
- ```ruby
656
- I18n.default_locale = :de
657
- ```
658
-
659
- ### Using Safe HTML Translations
660
-
661
- 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.
662
-
663
- ```yaml
664
- # config/locales/en.yml
665
- en:
666
- welcome: <b>welcome!</b>
667
- hello_html: <b>hello!</b>
668
- title:
669
- html: <b>title!</b>
670
- ```
671
-
672
- ```html+erb
673
- # app/views/home/index.html.erb
674
- <div><%= t('welcome') %></div>
675
- <div><%= raw t('welcome') %></div>
676
- <div><%= t('hello_html') %></div>
677
- <div><%= t('title.html') %></div>
678
- ```
679
-
680
- NOTE: Automatic conversion to HTML safe translate text is only available from the `translate` view helper method.
681
-
682
- ![i18n demo html safe](images/i18n/demo_html_safe.png)
683
-
684
- How to Store your Custom Translations
685
- -------------------------------------
686
-
687
- The Simple backend shipped with Active Support allows you to store translations in both plain Ruby and YAML format.[^2]
688
-
689
- For example a Ruby Hash providing translations can look like this:
690
-
691
- ```ruby
692
- {
693
- pt: {
694
- foo: {
695
- bar: "baz"
696
- }
697
- }
698
- }
699
- ```
700
-
701
- The equivalent YAML file would look like this:
702
-
703
- ```ruby
704
- pt:
705
- foo:
706
- bar: baz
707
- ```
708
-
709
- 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".
710
-
711
- Here is a "real" example from the Active Support `en.yml` translations YAML file:
712
-
713
- ```ruby
714
- en:
715
- date:
716
- formats:
717
- default: "%Y-%m-%d"
718
- short: "%b %d"
719
- long: "%B %d, %Y"
720
- ```
721
-
722
- So, all of the following equivalent lookups will return the `:short` date format `"%b %d"`:
723
-
724
- ```ruby
725
- I18n.t 'date.formats.short'
726
- I18n.t 'formats.short', scope: :date
727
- I18n.t :short, scope: 'date.formats'
728
- I18n.t :short, scope: [:date, :formats]
729
- ```
730
-
731
- 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.
732
-
733
- ### Translations for Active Record Models
734
-
735
- 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.
736
-
737
- For example when you add the following translations:
738
-
739
- ```ruby
740
- en:
741
- activerecord:
742
- models:
743
- user: Dude
744
- attributes:
745
- user:
746
- login: "Handle"
747
- # will translate User attribute "login" as "Handle"
748
- ```
749
-
750
- Then `User.model_name.human` will return "Dude" and `User.human_attribute_name("login")` will return "Handle".
751
-
752
- You can also set a plural form for model names, adding as following:
753
-
754
- ```ruby
755
- en:
756
- activerecord:
757
- models:
758
- user:
759
- one: Dude
760
- other: Dudes
761
- ```
762
-
763
- Then `User.model_name.human(count: 2)` will return "Dudes". With `count: 1` or without params will return "Dude".
764
-
765
- #### Error Message Scopes
766
-
767
- 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.
768
-
769
- This gives you quite powerful means to flexibly adjust your messages to your application's needs.
770
-
771
- Consider a User model with a validation for the name attribute like this:
772
-
773
- ```ruby
774
- class User < ActiveRecord::Base
775
- validates :name, presence: true
776
- end
777
- ```
778
-
779
- The key for the error message in this case is `:blank`. Active Record will look up this key in the namespaces:
780
-
781
- ```ruby
782
- activerecord.errors.models.[model_name].attributes.[attribute_name]
783
- activerecord.errors.models.[model_name]
784
- activerecord.errors.messages
785
- errors.attributes.[attribute_name]
786
- errors.messages
787
- ```
788
-
789
- Thus, in our example it will try the following keys in this order and return the first result:
790
-
791
- ```ruby
792
- activerecord.errors.models.user.attributes.name.blank
793
- activerecord.errors.models.user.blank
794
- activerecord.errors.messages.blank
795
- errors.attributes.name.blank
796
- errors.messages.blank
797
- ```
798
-
799
- When your models are additionally using inheritance then the messages are looked up in the inheritance chain.
800
-
801
- For example, you might have an Admin model inheriting from User:
802
-
803
- ```ruby
804
- class Admin < User
805
- validates :name, presence: true
806
- end
807
- ```
808
-
809
- Then Active Record will look for messages in this order:
810
-
811
- ```ruby
812
- activerecord.errors.models.admin.attributes.name.blank
813
- activerecord.errors.models.admin.blank
814
- activerecord.errors.models.user.attributes.name.blank
815
- activerecord.errors.models.user.blank
816
- activerecord.errors.messages.blank
817
- errors.attributes.name.blank
818
- errors.messages.blank
819
- ```
820
-
821
- 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.
822
-
823
- #### Error Message Interpolation
824
-
825
- The translated model name, translated attribute name, and value are always available for interpolation.
826
-
827
- 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}"`.
828
-
829
- * `count`, where available, can be used for pluralization if present:
830
-
831
- | validation | with option | message | interpolation |
832
- | ------------ | ------------------------- | ------------------------- | ------------- |
833
- | confirmation | - | :confirmation | - |
834
- | acceptance | - | :accepted | - |
835
- | presence | - | :blank | - |
836
- | absence | - | :present | - |
837
- | length | :within, :in | :too_short | count |
838
- | length | :within, :in | :too_long | count |
839
- | length | :is | :wrong_length | count |
840
- | length | :minimum | :too_short | count |
841
- | length | :maximum | :too_long | count |
842
- | uniqueness | - | :taken | - |
843
- | format | - | :invalid | - |
844
- | inclusion | - | :inclusion | - |
845
- | exclusion | - | :exclusion | - |
846
- | associated | - | :invalid | - |
847
- | numericality | - | :not_a_number | - |
848
- | numericality | :greater_than | :greater_than | count |
849
- | numericality | :greater_than_or_equal_to | :greater_than_or_equal_to | count |
850
- | numericality | :equal_to | :equal_to | count |
851
- | numericality | :less_than | :less_than | count |
852
- | numericality | :less_than_or_equal_to | :less_than_or_equal_to | count |
853
- | numericality | :only_integer | :not_an_integer | - |
854
- | numericality | :odd | :odd | - |
855
- | numericality | :even | :even | - |
856
-
857
- #### Translations for the Active Record `error_messages_for` Helper
858
-
859
- If you are using the Active Record `error_messages_for` helper, you will want to add
860
- translations for it.
861
-
862
- Rails ships with the following translations:
863
-
864
- ```yaml
865
- en:
866
- activerecord:
867
- errors:
868
- template:
869
- header:
870
- one: "1 error prohibited this %{model} from being saved"
871
- other: "%{count} errors prohibited this %{model} from being saved"
872
- body: "There were problems with the following fields:"
873
- ```
874
-
875
- NOTE: In order to use this helper, you need to install [DynamicForm](https://github.com/joelmoss/dynamic_form)
876
- gem by adding this line to your Gemfile: `gem 'dynamic_form'`.
877
-
878
- ### Translations for Action Mailer E-Mail Subjects
879
-
880
- If you don't pass a subject to the `mail` method, Action Mailer will try to find
881
- it in your translations. The performed lookup will use the pattern
882
- `<mailer_scope>.<action_name>.subject` to construct the key.
883
-
884
- ```ruby
885
- # user_mailer.rb
886
- class UserMailer < ActionMailer::Base
887
- def welcome(user)
888
- #...
889
- end
890
- end
891
- ```
892
-
893
- ```yaml
894
- en:
895
- user_mailer:
896
- welcome:
897
- subject: "Welcome to Rails Guides!"
898
- ```
899
-
900
- ### Overview of Other Built-In Methods that Provide I18n Support
901
-
902
- 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.
903
-
904
- #### Action View Helper Methods
905
-
906
- * `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.
907
-
908
- * `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.
909
-
910
- * 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.
911
-
912
- #### Active Model Methods
913
-
914
- * `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".
915
-
916
- * `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".
917
-
918
- * `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}"`).
919
-
920
- #### Active Support Methods
921
-
922
- * `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.
923
-
924
- Customize your I18n Setup
925
- -------------------------
926
-
927
- ### Using Different Backends
928
-
929
- 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.
930
-
931
- 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:
932
-
933
- ```ruby
934
- I18n.backend = Globalize::Backend::Static.new
935
- ```
936
-
937
- 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:
938
-
939
- ```ruby
940
- I18n.backend = I18n::Backend::Chain.new(I18n::Backend::ActiveRecord.new, I18n.backend)
941
- ```
942
-
943
- ### Using Different Exception Handlers
944
-
945
- The I18n API defines the following exceptions that will be raised by backends when the corresponding unexpected conditions occur:
946
-
947
- ```ruby
948
- MissingTranslationData # no translation was found for the requested key
949
- InvalidLocale # the locale set to I18n.locale is invalid (e.g. nil)
950
- InvalidPluralizationData # a count option was passed but the translation data is not suitable for pluralization
951
- MissingInterpolationArgument # the translation expects an interpolation argument that has not been passed
952
- ReservedInterpolationKey # the translation contains a reserved interpolation variable name (i.e. one of: scope, default)
953
- UnknownFileType # the backend does not know how to handle a file type that was added to I18n.load_path
954
- ```
955
-
956
- 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.
957
-
958
- The reason for this is that during development you'd usually want your views to still render even though a translation is missing.
959
-
960
- 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:
961
-
962
- ```ruby
963
- module I18n
964
- class JustRaiseExceptionHandler < ExceptionHandler
965
- def call(exception, locale, key, options)
966
- if exception.is_a?(MissingTranslation)
967
- raise exception.to_exception
968
- else
969
- super
970
- end
971
- end
972
- end
973
- end
974
-
975
- I18n.exception_handler = I18n::JustRaiseExceptionHandler.new
976
- ```
977
-
978
- This would re-raise only the `MissingTranslationData` exception, passing all other input to the default exception handler.
979
-
980
- 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:
981
-
982
- ```ruby
983
- if exception.is_a?(MissingTranslation) && key.to_s != 'i18n.plural.rule'
984
- raise exception.to_exception
985
- else
986
- super
987
- end
988
- ```
989
-
990
- 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`.
991
-
992
- To do so, the helper forces `I18n#translate` to raise exceptions no matter what exception handler is defined by setting the `:raise` option:
993
-
994
- ```ruby
995
- I18n.t :foo, raise: true # always re-raises exceptions from the backend
996
- ```
997
-
998
- Conclusion
999
- ----------
1000
-
1001
- 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.
1002
-
1003
- 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).
1004
-
1005
-
1006
- Contributing to Rails I18n
1007
- --------------------------
1008
-
1009
- 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.
1010
-
1011
- 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!))
1012
-
1013
- 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).
1014
-
1015
-
1016
- Resources
1017
- ---------
1018
-
1019
- * [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).
1020
- * [Google group: rails-i18n](http://groups.google.com/group/rails-i18n) - The project's mailing list.
1021
- * [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.
1022
- * [GitHub: i18n](https://github.com/svenfuchs/i18n/tree/master) - Code repository for the i18n gem.
1023
- * [Lighthouse: rails-i18n](http://i18n.lighthouseapp.com/projects/14948-rails-i18n/overview) - Issue tracker for the rails-i18n project.
1024
- * [Lighthouse: i18n](http://i18n.lighthouseapp.com/projects/14947-ruby-i18n/overview) - Issue tracker for the i18n gem.
1025
-
1026
-
1027
- Authors
1028
- -------
1029
-
1030
- * [Sven Fuchs](http://www.workingwithrails.com/person/9963-sven-fuchs) (initial author)
1031
- * [Karel Minařík](http://www.workingwithrails.com/person/7476-karel-mina-k)
1032
-
1033
- If you found this guide useful, please consider recommending its authors on [workingwithrails](http://www.workingwithrails.com).
1034
-
1035
-
1036
- Footnotes
1037
- ---------
1038
-
1039
- [^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."_
1040
-
1041
- [^2]: Other backends might allow or require to use other formats, e.g. a GetText backend might allow to read GetText files.
1042
-
1043
- [^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.