CINXE.COM
Rails Internationalization (I18n) API — Ruby on Rails Guides
<!doctype html> <html dir="ltr" lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>Rails Internationalization (I18n) API — Ruby on Rails Guides</title> <link rel="stylesheet" type="text/css" href="stylesheets/style-6fc5bf25e695f363fd1dd3d9dbb2f997.css" data-turbo-track="reload"> <link rel="stylesheet" type="text/css" href="stylesheets/print-a87ee66d50ce96bb83ac082f1249fe3e.css" media="print"> <link rel="stylesheet" type="text/css" href="stylesheets/highlight-2794201d063bd2e4dbd0f0874c2a3f6f.css" data-turbo-track="reload"> <link rel="icon" href="images/favicon.ico" sizes="any"> <link rel="apple-touch-icon" href="images/icon.png"> <link rel="canonical" href="https://guides.rubyonrails.org/i18n.html"> <script src="javascripts/@hotwired--turbo-764f59c7edbeb902a9068c0340dd274e.js" data-turbo-track="reload"></script> <script src="javascripts/clipboard-8b7aed6f069f0cf58eeae353cd2f898b.js" data-turbo-track="reload"></script> <script src="javascripts/guides-751b87e159daf790ddf7e8e88ad8465a.js" data-turbo-track="reload"></script> <meta property="og:title" content="Rails Internationalization (I18n) API — Ruby on Rails Guides" /> <meta name="description" content="Rails Internationalization (I18n) APIThe 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.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.1So, in the process of internationalizing your Rails application you have to: Ensure you have support for I18n. Tell Rails where to find locale dictionaries. Tell Rails how to set, preserve, and switch locales. In the process of localizing your application you'll probably want to do the following three things: Replace or supplement Rails' default locale - e.g. date and time formats, month names, Active Record model names, etc. Abstract strings in your application into keyed dictionaries - e.g. flash messages, static text in your views, etc. Store the resulting dictionaries somewhere. This guide will walk you through the I18n API and contains a tutorial on how to internationalize a Rails application from the start.After reading this guide, you will know: How I18n works in Ruby on Rails How to correctly use I18n in a RESTful application in various ways How to use I18n to translate Active Record errors or Action Mailer E-mail subjects Some other tools to go further with the translation process of your application" /> <meta property="og:description" content="Rails Internationalization (I18n) APIThe 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.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.1So, in the process of internationalizing your Rails application you have to: Ensure you have support for I18n. Tell Rails where to find locale dictionaries. Tell Rails how to set, preserve, and switch locales. In the process of localizing your application you'll probably want to do the following three things: Replace or supplement Rails' default locale - e.g. date and time formats, month names, Active Record model names, etc. Abstract strings in your application into keyed dictionaries - e.g. flash messages, static text in your views, etc. Store the resulting dictionaries somewhere. This guide will walk you through the I18n API and contains a tutorial on how to internationalize a Rails application from the start.After reading this guide, you will know: How I18n works in Ruby on Rails How to correctly use I18n in a RESTful application in various ways How to use I18n to translate Active Record errors or Action Mailer E-mail subjects Some other tools to go further with the translation process of your application" /> <meta property="og:locale" content="en_US" /> <meta property="og:site_name" content="Ruby on Rails Guides" /> <meta property="og:image" content="https://avatars.githubusercontent.com/u/4223" /> <meta property="og:type" content="website" /> <link rel="preconnect" href="https://fonts.googleapis.com"> <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin> <link href="https://fonts.googleapis.com/css2?family=Noto+Sans+Arabic:wght@100..900&display=swap" rel="stylesheet"> <link href="https://fonts.googleapis.com/css2?family=Heebo:wght@100..900&family=Noto+Sans+Arabic:wght@100..900&display=swap" rel="stylesheet"> <meta name="theme-color" content="#C81418"> </head> <body dir="ltr" class="guide no-js"> <script> document.body.classList.remove('no-js') </script> <a id="main-skip-link" href="#main" class="skip-link" data-turbo="false"> Skip to main content </a> <div id="mobile-navigation-bar"> <div class="wrapper"> <strong class="more-info-label">More at <a href="https://rubyonrails.org/">rubyonrails.org:</a> </strong> <button type="button" class="js-only red-button more-info-button" id="more-info" aria-controls="more-info-links" aria-expanded="false"> More Ruby on Rails </button> <ul id="more-info-links" class="more-info-links hidden"> <li class="more-info"><a href="https://rubyonrails.org/blog">Blog</a></li> <li class="more-info"><a href="https://guides.rubyonrails.org/">Guides</a></li> <li class="more-info"><a href="https://api.rubyonrails.org/">API</a></li> <li class="more-info"><a href="https://discuss.rubyonrails.org/">Forum</a></li> <li class="more-info"><a href="https://github.com/rails/rails">Contribute on GitHub</a></li> </ul> </div> </div> <header id="page-header"> <div class="wrapper clearfix"> <nav id="feature-nav"> <div class="header-logo"> <a href="index.html" title="Guides home for v8.0.1 Guides">Guides</a> <span id="version-switcher" class="js-only"> <label for="version-switcher-select">Version: <span class="visibly-hidden">pick from the list to go to that Rails version's guides</span></label> <select id="version-switcher-select" class="guides-version"> <option value="https://edgeguides.rubyonrails.org/">Edge</option> <option value="https://guides.rubyonrails.org/v8.0/i18n.html" selected>8.0</option> <option value="https://guides.rubyonrails.org/v7.2/i18n.html">7.2</option> <option value="https://guides.rubyonrails.org/v7.1/i18n.html">7.1</option> <option value="https://guides.rubyonrails.org/v7.0/i18n.html">7.0</option> <option value="https://guides.rubyonrails.org/v6.1/i18n.html">6.1</option> <option value="https://guides.rubyonrails.org/v6.0/i18n.html">6.0</option> <option value="https://guides.rubyonrails.org/v5.2/i18n.html">5.2</option> <option value="https://guides.rubyonrails.org/v5.1/i18n.html">5.1</option> <option value="https://guides.rubyonrails.org/v5.0/i18n.html">5.0</option> <option value="https://guides.rubyonrails.org/v4.2/i18n.html">4.2</option> <option value="https://guides.rubyonrails.org/v4.1/i18n.html">4.1</option> <option value="https://guides.rubyonrails.org/v4.0/i18n.html">4.0</option> <option value="https://guides.rubyonrails.org/v3.2/i18n.html">3.2</option> <option value="https://guides.rubyonrails.org/v3.1/i18n.html">3.1</option> <option value="https://guides.rubyonrails.org/v3.0/i18n.html">3.0</option> <option value="https://guides.rubyonrails.org/v2.3/i18n.html">2.3</option> </select> </span> </div> <ul class="nav"> <li><a class="nav-item" id="home_nav" href="https://rubyonrails.org/">Home</a></li> <li class="guides-index guides-index-large"> <a href="index.html" id="guides-menu-button" data-aria-controls="guides" data-aria-expanded="false" class="guides-index-item nav-item">Guides Index</a> <div id="guides" class="clearfix" style="display: none;"> <hr /> <dl class="guides-section-container"> <div class="guides-section"> <dt>Start Here</dt> <dd><a href="getting_started.html">Getting Started with Rails</a></dd> <dd><a href="install_ruby_on_rails.html">Install Ruby on Rails</a></dd> </div> <div class="guides-section"> <dt>Models</dt> <dd><a href="active_record_basics.html">Active Record Basics</a></dd> <dd><a href="active_record_migrations.html">Active Record Migrations</a></dd> <dd><a href="active_record_validations.html">Active Record Validations</a></dd> <dd><a href="active_record_callbacks.html">Active Record Callbacks</a></dd> <dd><a href="association_basics.html">Active Record Associations</a></dd> <dd><a href="active_record_querying.html">Active Record Query Interface</a></dd> <dd><a href="active_model_basics.html">Active Model Basics</a></dd> </div> <div class="guides-section"> <dt>Views</dt> <dd><a href="action_view_overview.html">Action View Overview</a></dd> <dd><a href="layouts_and_rendering.html">Layouts and Rendering in Rails</a></dd> <dd><a href="action_view_helpers.html">Action View Helpers</a></dd> <dd><a href="form_helpers.html">Action View Form Helpers</a></dd> </div> <div class="guides-section"> <dt>Controllers</dt> <dd><a href="action_controller_overview.html">Action Controller Overview</a></dd> <dd><a href="action_controller_advanced_topics.html">Action Controller Advanced Topics</a></dd> <dd><a href="routing.html">Rails Routing from the Outside In</a></dd> </div> <div class="guides-section"> <dt>Other Components</dt> <dd><a href="active_support_core_extensions.html">Active Support Core Extensions</a></dd> <dd><a href="action_mailer_basics.html">Action Mailer Basics</a></dd> <dd><a href="action_mailbox_basics.html">Action Mailbox Basics</a></dd> <dd><a href="action_text_overview.html">Action Text Overview</a></dd> <dd><a href="active_job_basics.html">Active Job Basics</a></dd> <dd><a href="active_storage_overview.html">Active Storage Overview</a></dd> <dd><a href="action_cable_overview.html">Action Cable Overview</a></dd> </div> <div class="guides-section"> <dt>Digging Deeper</dt> <dd><a href="i18n.html">Rails Internationalization (I18n) API</a></dd> <dd><a href="testing.html">Testing Rails Applications</a></dd> <dd><a href="debugging_rails_applications.html">Debugging Rails Applications</a></dd> <dd><a href="configuring.html">Configuring Rails Applications</a></dd> <dd><a href="command_line.html">The Rails Command Line</a></dd> <dd><a href="asset_pipeline.html">The Asset Pipeline</a></dd> <dd><a href="working_with_javascript_in_rails.html">Working with JavaScript in Rails</a></dd> <dd><a href="autoloading_and_reloading_constants.html">Autoloading and Reloading</a></dd> <dd><a href="api_app.html">Using Rails for API-only Applications</a></dd> </div> <div class="guides-section"> <dt>Going to Production</dt> <dd><a href="tuning_performance_for_deployment.html">Tuning Performance for Deployment</a></dd> <dd><a href="caching_with_rails.html">Caching with Rails: An Overview</a></dd> <dd><a href="security.html">Securing Rails Applications</a></dd> <dd><a href="error_reporting.html">Error Reporting in Rails Applications</a></dd> </div> <div class="guides-section"> <dt>Advanced Active Record</dt> <dd><a href="active_record_multiple_databases.html">Multiple Databases</a></dd> <dd><a href="active_record_composite_primary_keys.html">Composite Primary Keys</a></dd> </div> <div class="guides-section"> <dt>Extending Rails</dt> <dd><a href="rails_on_rack.html">Rails on Rack</a></dd> <dd><a href="generators.html">Creating and Customizing Rails Generators & Templates</a></dd> </div> <div class="guides-section"> <dt>Contributing</dt> <dd><a href="contributing_to_ruby_on_rails.html">Contributing to Ruby on Rails</a></dd> <dd><a href="api_documentation_guidelines.html">API Documentation Guidelines</a></dd> <dd><a href="ruby_on_rails_guides_guidelines.html">Guides Guidelines</a></dd> <dd><a href="development_dependencies_install.html">Installing Rails Core Development Dependencies</a></dd> </div> <div class="guides-section"> <dt>Policies</dt> <dd><a href="maintenance_policy.html">Maintenance Policy</a></dd> </div> <div class="guides-section"> <dt>Release Notes</dt> <dd><a href="upgrading_ruby_on_rails.html">Upgrading Ruby on Rails</a></dd> <dd><a href="8_0_release_notes.html">Version 8.0 - November 2024</a></dd> <dd><a href="7_2_release_notes.html">Version 7.2 - August 2024</a></dd> <dd><a href="7_1_release_notes.html">Version 7.1 - October 2023</a></dd> <dd><a href="7_0_release_notes.html">Version 7.0 - December 2021</a></dd> <dd><a href="6_1_release_notes.html">Version 6.1 - December 2020</a></dd> <dd><a href="6_0_release_notes.html">Version 6.0 - August 2019</a></dd> <dd><a href="5_2_release_notes.html">Version 5.2 - April 2018</a></dd> <dd><a href="5_1_release_notes.html">Version 5.1 - April 2017</a></dd> <dd><a href="5_0_release_notes.html">Version 5.0 - June 2016</a></dd> <dd><a href="4_2_release_notes.html">Version 4.2 - December 2014</a></dd> <dd><a href="4_1_release_notes.html">Version 4.1 - April 2014</a></dd> <dd><a href="4_0_release_notes.html">Version 4.0 - June 2013</a></dd> <dd><a href="3_2_release_notes.html">Version 3.2 - January 2012</a></dd> <dd><a href="3_1_release_notes.html">Version 3.1 - August 2011</a></dd> <dd><a href="3_0_release_notes.html">Version 3.0 - August 2010</a></dd> <dd><a href="2_3_release_notes.html">Version 2.3 - March 2009</a></dd> <dd><a href="2_2_release_notes.html">Version 2.2 - November 2008</a></dd> </div> </dl> </div> </li> <li><a class="nav-item" href="contributing_to_ruby_on_rails.html">Contribute</a></li> <li class="guides-index guides-index-small js-only"> <label for="guides-selector"> Navigate to a guide: </label> <select id="guides-selector" class="guides-index-item nav-item"> <option value="index.html">Guides Index</option> <optgroup label="Start Here"> <option value="getting_started.html">Getting Started with Rails</option> <option value="install_ruby_on_rails.html">Install Ruby on Rails</option> </optgroup> <optgroup label="Models"> <option value="active_record_basics.html">Active Record Basics</option> <option value="active_record_migrations.html">Active Record Migrations</option> <option value="active_record_validations.html">Active Record Validations</option> <option value="active_record_callbacks.html">Active Record Callbacks</option> <option value="association_basics.html">Active Record Associations</option> <option value="active_record_querying.html">Active Record Query Interface</option> <option value="active_model_basics.html">Active Model Basics</option> </optgroup> <optgroup label="Views"> <option value="action_view_overview.html">Action View Overview</option> <option value="layouts_and_rendering.html">Layouts and Rendering in Rails</option> <option value="action_view_helpers.html">Action View Helpers</option> <option value="form_helpers.html">Action View Form Helpers</option> </optgroup> <optgroup label="Controllers"> <option value="action_controller_overview.html">Action Controller Overview</option> <option value="action_controller_advanced_topics.html">Action Controller Advanced Topics</option> <option value="routing.html">Rails Routing from the Outside In</option> </optgroup> <optgroup label="Other Components"> <option value="active_support_core_extensions.html">Active Support Core Extensions</option> <option value="action_mailer_basics.html">Action Mailer Basics</option> <option value="action_mailbox_basics.html">Action Mailbox Basics</option> <option value="action_text_overview.html">Action Text Overview</option> <option value="active_job_basics.html">Active Job Basics</option> <option value="active_storage_overview.html">Active Storage Overview</option> <option value="action_cable_overview.html">Action Cable Overview</option> </optgroup> <optgroup label="Digging Deeper"> <option value="i18n.html">Rails Internationalization (I18n) API</option> <option value="testing.html">Testing Rails Applications</option> <option value="debugging_rails_applications.html">Debugging Rails Applications</option> <option value="configuring.html">Configuring Rails Applications</option> <option value="command_line.html">The Rails Command Line</option> <option value="asset_pipeline.html">The Asset Pipeline</option> <option value="working_with_javascript_in_rails.html">Working with JavaScript in Rails</option> <option value="autoloading_and_reloading_constants.html">Autoloading and Reloading</option> <option value="api_app.html">Using Rails for API-only Applications</option> </optgroup> <optgroup label="Going to Production"> <option value="tuning_performance_for_deployment.html">Tuning Performance for Deployment</option> <option value="caching_with_rails.html">Caching with Rails: An Overview</option> <option value="security.html">Securing Rails Applications</option> <option value="error_reporting.html">Error Reporting in Rails Applications</option> </optgroup> <optgroup label="Advanced Active Record"> <option value="active_record_multiple_databases.html">Multiple Databases</option> <option value="active_record_composite_primary_keys.html">Composite Primary Keys</option> </optgroup> <optgroup label="Extending Rails"> <option value="rails_on_rack.html">Rails on Rack</option> <option value="generators.html">Creating and Customizing Rails Generators & Templates</option> </optgroup> <optgroup label="Contributing"> <option value="contributing_to_ruby_on_rails.html">Contributing to Ruby on Rails</option> <option value="api_documentation_guidelines.html">API Documentation Guidelines</option> <option value="ruby_on_rails_guides_guidelines.html">Guides Guidelines</option> <option value="development_dependencies_install.html">Installing Rails Core Development Dependencies</option> </optgroup> <optgroup label="Policies"> <option value="maintenance_policy.html">Maintenance Policy</option> </optgroup> <optgroup label="Release Notes"> <option value="upgrading_ruby_on_rails.html">Upgrading Ruby on Rails</option> <option value="8_0_release_notes.html">Version 8.0 - November 2024</option> <option value="7_2_release_notes.html">Version 7.2 - August 2024</option> <option value="7_1_release_notes.html">Version 7.1 - October 2023</option> <option value="7_0_release_notes.html">Version 7.0 - December 2021</option> <option value="6_1_release_notes.html">Version 6.1 - December 2020</option> <option value="6_0_release_notes.html">Version 6.0 - August 2019</option> <option value="5_2_release_notes.html">Version 5.2 - April 2018</option> <option value="5_1_release_notes.html">Version 5.1 - April 2017</option> <option value="5_0_release_notes.html">Version 5.0 - June 2016</option> <option value="4_2_release_notes.html">Version 4.2 - December 2014</option> <option value="4_1_release_notes.html">Version 4.1 - April 2014</option> <option value="4_0_release_notes.html">Version 4.0 - June 2013</option> <option value="3_2_release_notes.html">Version 3.2 - January 2012</option> <option value="3_1_release_notes.html">Version 3.1 - August 2011</option> <option value="3_0_release_notes.html">Version 3.0 - August 2010</option> <option value="2_3_release_notes.html">Version 2.3 - March 2009</option> <option value="2_2_release_notes.html">Version 2.2 - November 2008</option> </optgroup> </select> </li> </ul> </nav> </div> </header> <hr class="hide" /> <main id="main"> <article> <header id="feature"> <div class="wrapper"> <h1>Rails Internationalization (I18n) API</h1><p>The Ruby I18n (shorthand for <em>internationalization</em>) gem which is shipped with Ruby on Rails (starting from Rails 2.2) provides an easy-to-use and extensible framework for <strong>translating your application to a single custom language</strong> other than English or for <strong>providing multi-language support</strong> in your application.</p><p>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.<sup class="footnote" id="footnote-1-ref"><a href="#footnote-1">1</a></sup></p><p>So, in the process of <em>internationalizing</em> your Rails application you have to:</p> <ul> <li>Ensure you have support for I18n.</li> <li>Tell Rails where to find locale dictionaries.</li> <li>Tell Rails how to set, preserve, and switch locales.</li> </ul> <p>In the process of <em>localizing</em> your application you'll probably want to do the following three things:</p> <ul> <li>Replace or supplement Rails' default locale - e.g. date and time formats, month names, Active Record model names, etc.</li> <li>Abstract strings in your application into keyed dictionaries - e.g. flash messages, static text in your views, etc.</li> <li>Store the resulting dictionaries somewhere.</li> </ul> <p>This guide will walk you through the I18n API and contains a tutorial on how to internationalize a Rails application from the start.</p><p>After reading this guide, you will know:</p> <ul> <li>How I18n works in Ruby on Rails</li> <li>How to correctly use I18n in a RESTful application in various ways</li> <li>How to use I18n to translate Active Record errors or Action Mailer E-mail subjects</li> <li>Some other tools to go further with the translation process of your application</li> </ul> <nav id="column-side" aria-label="Chapter" class="guide-index" data-turbo="false"> <a id="chapter-nav-skip-link" href="#article-body" class="skip-link"> Skip to article body </a> <h2 class="chapter"> <picture aria-hidden="true"> <!-- Using the `source` HTML tag to set the dark theme image --> <source srcset="images/icon_book-close-bookmark-1-wht.svg" media="(prefers-color-scheme: dark)" /> <img src="images/icon_book-close-bookmark-1.svg" alt="Chapter Icon" /> </picture> Chapters </h2> <ol class="chapters"> <li><a href="#how-i18n-in-ruby-on-rails-works">How I18n in Ruby on Rails Works</a> <ul> <li><a href="#the-overall-architecture-of-the-library">The Overall Architecture of the Library</a></li> <li><a href="#the-public-i18n-api">The Public I18n API</a></li> </ul></li> <li><a href="#setup-the-rails-application-for-internationalization">Setup the Rails Application for Internationalization</a> <ul> <li><a href="#configure-the-i18n-module">Configure the I18n Module</a></li> <li><a href="#managing-the-locale-across-requests">Managing the Locale across Requests</a></li> </ul></li> <li><a href="#internationalization-and-localization">Internationalization and Localization</a> <ul> <li><a href="#abstracting-localized-code">Abstracting Localized Code</a></li> <li><a href="#providing-translations-for-internationalized-strings">Providing Translations for Internationalized Strings</a></li> <li><a href="#passing-variables-to-translations">Passing Variables to Translations</a></li> <li><a href="#adding-date-time-formats">Adding Date/Time Formats</a></li> <li><a href="#inflection-rules-for-other-locales">Inflection Rules for Other Locales</a></li> <li><a href="#localized-views">Localized Views</a></li> <li><a href="#organization-of-locale-files">Organization of Locale Files</a></li> </ul></li> <li><a href="#overview-of-the-i18n-api-features">Overview of the I18n API Features</a> <ul> <li><a href="#looking-up-translations">Looking up Translations</a></li> <li><a href="#pluralization">Pluralization</a></li> <li><a href="#setting-and-passing-a-locale">Setting and Passing a Locale</a></li> <li><a href="#using-safe-html-translations">Using Safe HTML Translations</a></li> <li><a href="#translations-for-active-record-models">Translations for Active Record Models</a></li> <li><a href="#translations-for-action-mailer-e-mail-subjects">Translations for Action Mailer E-Mail Subjects</a></li> <li><a href="#overview-of-other-built-in-methods-that-provide-i18n-support">Overview of Other Built-In Methods that Provide I18n Support</a></li> </ul></li> <li><a href="#how-to-store-your-custom-translations">How to Store your Custom Translations</a></li> <li><a href="#customize-your-i18n-setup">Customize Your I18n Setup</a> <ul> <li><a href="#using-different-backends">Using Different Backends</a></li> <li><a href="#using-different-exception-handlers">Using Different Exception Handlers</a></li> </ul></li> <li><a href="#translating-model-content">Translating Model Content</a></li> <li><a href="#conclusion">Conclusion</a></li> <li><a href="#contributing-to-rails-i18n">Contributing to Rails I18n</a></li> <li><a href="#resources">Resources</a></li> <li><a href="#authors">Authors</a></li> <li><a href="#footnotes">Footnotes</a></li> </ol> </nav> </div> </header> <div class="wrapper"> <div id="column-main"> <section id="article-body"> <div class="interstitial note"><p>The Ruby I18n framework provides you with all necessary means for internationalization/localization of your Rails application. You may also use various gems available to add additional functionality or features. See the <a href="https://github.com/svenfuchs/rails-i18n">rails-i18n gem</a> for more information.</p></div><h2 id="how-i18n-in-ruby-on-rails-works"><a class="anchorlink" href="#how-i18n-in-ruby-on-rails-works" data-turbo="false"><span>1</span> How I18n in Ruby on Rails Works</a></h2><p>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:</p> <ul> <li>providing support for English and similar languages out of the box</li> <li>making it easy to customize and extend everything for other languages</li> </ul> <p>As part of this solution, <strong>every static string in the Rails framework</strong> - e.g. Active Record validation messages, time and date formats - <strong>has been internationalized</strong>. <em>Localization</em> of a Rails application means defining translated values for these strings in desired languages.</p><p>To localize, store, and update <em>content</em> in your application (e.g. translate blog posts), see the <a href="#translating-model-content">Translating model content</a> section.</p><h3 id="the-overall-architecture-of-the-library"><a class="anchorlink" href="#the-overall-architecture-of-the-library" data-turbo="false"><span>1.1</span> The Overall Architecture of the Library</a></h3><p>Thus, the Ruby I18n gem is split into two parts:</p> <ul> <li>The public API of the I18n framework - a Ruby module with public methods that define how the library works</li> <li>A default backend (which is intentionally named <em>Simple</em> backend) that implements these methods</li> </ul> <p>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.</p><div class="interstitial note"><p>It is possible 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 <a href="#using-different-backends">Using different backends</a> below.</p></div><h3 id="the-public-i18n-api"><a class="anchorlink" href="#the-public-i18n-api" data-turbo="false"><span>1.2</span> The Public I18n API</a></h3><p>The most important methods of the I18n API are:</p><div class="interstitial code"> <pre><code class="highlight ruby"><span class="n">translate</span> <span class="c1"># Lookup text translations</span> <span class="n">localize</span> <span class="c1"># Localize Date and Time objects to local formats</span> </code></pre> <button class="clipboard-button" data-clipboard-text="translate # Lookup text translations localize # Localize Date and Time objects to local formats ">Copy</button> </div> <p>These have the aliases #t and #l so you can use them like this:</p><div class="interstitial code"> <pre><code class="highlight ruby"><span class="no">I18n</span><span class="p">.</span><span class="nf">t</span> <span class="s2">"store.title"</span> <span class="no">I18n</span><span class="p">.</span><span class="nf">l</span> <span class="no">Time</span><span class="p">.</span><span class="nf">now</span> </code></pre> <button class="clipboard-button" data-clipboard-text="I18n.t "store.title" I18n.l Time.now ">Copy</button> </div> <p>There are also attribute readers and writers for the following attributes:</p><div class="interstitial code"> <pre><code class="highlight ruby"><span class="n">load_path</span> <span class="c1"># Announce your custom translation files</span> <span class="n">locale</span> <span class="c1"># Get and set the current locale</span> <span class="n">default_locale</span> <span class="c1"># Get and set the default locale</span> <span class="n">available_locales</span> <span class="c1"># Permitted locales available for the application</span> <span class="n">enforce_available_locales</span> <span class="c1"># Enforce locale permission (true or false)</span> <span class="n">exception_handler</span> <span class="c1"># Use a different exception_handler</span> <span class="n">backend</span> <span class="c1"># Use a different backend</span> </code></pre> <button class="clipboard-button" data-clipboard-text="load_path # Announce your custom translation files locale # Get and set the current locale default_locale # Get and set the default locale available_locales # Permitted locales available for the application enforce_available_locales # Enforce locale permission (true or false) exception_handler # Use a different exception_handler backend # Use a different backend ">Copy</button> </div> <p>So, let's internationalize a simple Rails application from the ground up in the next chapters!</p><h2 id="setup-the-rails-application-for-internationalization"><a class="anchorlink" href="#setup-the-rails-application-for-internationalization" data-turbo="false"><span>2</span> Setup the Rails Application for Internationalization</a></h2><p>There are a few steps to get up and running with I18n support for a Rails application.</p><h3 id="configure-the-i18n-module"><a class="anchorlink" href="#configure-the-i18n-module" data-turbo="false"><span>2.1</span> Configure the I18n Module</a></h3><p>Following the <em>convention over configuration</em> philosophy, Rails I18n provides reasonable default translation strings. When different translation strings are needed, they can be overridden.</p><p>Rails adds all <code>.rb</code> and <code>.yml</code> files from the <code>config/locales</code> directory to the <strong>translations load path</strong>, automatically.</p><p>The default <code>en.yml</code> locale in this directory contains a sample pair of translation strings:</p><div class="interstitial code"> <pre><code class="highlight yaml"><span class="na">en</span><span class="pi">:</span> <span class="na">hello</span><span class="pi">:</span> <span class="s2">"</span><span class="s">Hello</span><span class="nv"> </span><span class="s">world"</span> </code></pre> <button class="clipboard-button" data-clipboard-text="en: hello: "Hello world" ">Copy</button> </div> <p>This means, that in the <code>:en</code> locale, the key <em>hello</em> will map to the <em>Hello world</em> string. Every string inside Rails is internationalized in this way, see for instance Active Model validation messages in the <a href="https://github.com/rails/rails/blob/main/activemodel/lib/active_model/locale/en.yml"><code>activemodel/lib/active_model/locale/en.yml</code></a> file or time and date formats in the <a href="https://github.com/rails/rails/blob/main/activesupport/lib/active_support/locale/en.yml"><code>activesupport/lib/active_support/locale/en.yml</code></a> file. You can use YAML or standard Ruby Hashes to store translations in the default (Simple) backend.</p><p>The I18n library will use <strong>English</strong> as a <strong>default locale</strong>, i.e. if a different locale is not set, <code>:en</code> will be used for looking up translations.</p><div class="interstitial note"><p>The i18n library takes a <strong>pragmatic approach</strong> to locale keys (after <a href="https://groups.google.com/g/rails-i18n/c/FN7eLH2-lHA">some discussion</a>), including only the <em>locale</em> ("language") part, like <code>:en</code>, <code>:pl</code>, not the <em>region</em> part, like <code>:"en-US"</code> or <code>:"en-GB"</code>, 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 <code>:cs</code>, <code>:th</code>, or <code>:es</code> (for Czech, Thai, and Spanish). However, there are also regional differences within different language groups that may be important. For instance, in the <code>:"en-US"</code> locale you would have $ as a currency symbol, while in <code>:"en-GB"</code>, 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 <code>:"en-GB"</code> dictionary.</p></div><p>The <strong>translations load path</strong> (<code>I18n.load_path</code>) is an array of paths to files that will be loaded automatically. Configuring this path allows for customization of translations directory structure and file naming scheme.</p><div class="interstitial note"><p>The backend lazy-loads these translations when a translation is looked up for the first time. This backend can be swapped with something else even after translations have already been announced.</p></div><p>You can change the default locale as well as configure the translations load paths in <code>config/application.rb</code> as follows:</p><div class="interstitial code"> <pre><code class="highlight ruby"><span class="n">config</span><span class="p">.</span><span class="nf">i18n</span><span class="p">.</span><span class="nf">load_path</span> <span class="o">+=</span> <span class="no">Dir</span><span class="p">[</span><span class="no">Rails</span><span class="p">.</span><span class="nf">root</span><span class="p">.</span><span class="nf">join</span><span class="p">(</span><span class="s2">"my"</span><span class="p">,</span> <span class="s2">"locales"</span><span class="p">,</span> <span class="s2">"*.{rb,yml}"</span><span class="p">)]</span> <span class="n">config</span><span class="p">.</span><span class="nf">i18n</span><span class="p">.</span><span class="nf">default_locale</span> <span class="o">=</span> <span class="ss">:de</span> </code></pre> <button class="clipboard-button" data-clipboard-text="config.i18n.load_path += Dir[Rails.root.join("my", "locales", "*.{rb,yml}")] config.i18n.default_locale = :de ">Copy</button> </div> <p>The load path must be specified before any translations are looked up. To change the default locale from an initializer instead of <code>config/application.rb</code>:</p><div class="interstitial code"> <pre><code class="highlight ruby"><span class="c1"># config/initializers/locale.rb</span> <span class="c1"># Where the I18n library should search for translation files</span> <span class="no">I18n</span><span class="p">.</span><span class="nf">load_path</span> <span class="o">+=</span> <span class="no">Dir</span><span class="p">[</span><span class="no">Rails</span><span class="p">.</span><span class="nf">root</span><span class="p">.</span><span class="nf">join</span><span class="p">(</span><span class="s2">"lib"</span><span class="p">,</span> <span class="s2">"locale"</span><span class="p">,</span> <span class="s2">"*.{rb,yml}"</span><span class="p">)]</span> <span class="c1"># Permitted locales available for the application</span> <span class="no">I18n</span><span class="p">.</span><span class="nf">available_locales</span> <span class="o">=</span> <span class="p">[</span><span class="ss">:en</span><span class="p">,</span> <span class="ss">:pt</span><span class="p">]</span> <span class="c1"># Set default locale to something other than :en</span> <span class="no">I18n</span><span class="p">.</span><span class="nf">default_locale</span> <span class="o">=</span> <span class="ss">:pt</span> </code></pre> <button class="clipboard-button" data-clipboard-text=" # Where the I18n library should search for translation files I18n.load_path += Dir[Rails.root.join("lib", "locale", "*.{rb,yml}")] # Permitted locales available for the application I18n.available_locales = [:en, :pt] # Set default locale to something other than :en I18n.default_locale = :pt ">Copy</button> </div> <p>Note that appending directly to <code>I18n.load_path</code> instead of to the application's configured I18n will <em>not</em> override translations from external gems.</p><h3 id="managing-the-locale-across-requests"><a class="anchorlink" href="#managing-the-locale-across-requests" data-turbo="false"><span>2.2</span> Managing the Locale across Requests</a></h3><p>A localized application will likely need to provide support for multiple locales. To accomplish this, the locale should be set at the beginning of each request so that all strings are translated using the desired locale during the lifetime of that request.</p><p>The default locale is used for all translations unless <code>I18n.locale=</code> or <code>I18n.with_locale</code> is used.</p><p><code>I18n.locale</code> can leak into subsequent requests served by the same thread/process if it is not consistently set in every controller. For example executing <code>I18n.locale = :es</code> in one POST requests will have effects for all later requests to controllers that don't set the locale, but only in that particular thread/process. For that reason, instead of <code>I18n.locale =</code> you can use <code>I18n.with_locale</code> which does not have this leak issue.</p><p>The locale can be set in an <code>around_action</code> in the <code>ApplicationController</code>:</p><div class="interstitial code"> <pre><code class="highlight ruby"><span class="n">around_action</span> <span class="ss">:switch_locale</span> <span class="k">def</span> <span class="nf">switch_locale</span><span class="p">(</span><span class="o">&</span><span class="n">action</span><span class="p">)</span> <span class="n">locale</span> <span class="o">=</span> <span class="n">params</span><span class="p">[</span><span class="ss">:locale</span><span class="p">]</span> <span class="o">||</span> <span class="no">I18n</span><span class="p">.</span><span class="nf">default_locale</span> <span class="no">I18n</span><span class="p">.</span><span class="nf">with_locale</span><span class="p">(</span><span class="n">locale</span><span class="p">,</span> <span class="o">&</span><span class="n">action</span><span class="p">)</span> <span class="k">end</span> </code></pre> <button class="clipboard-button" data-clipboard-text="around_action :switch_locale def switch_locale(&action) locale = params[:locale] || I18n.default_locale I18n.with_locale(locale, &action) end ">Copy</button> </div> <p>This example illustrates this using a URL query parameter to set the locale (e.g. <code>http://example.com/books?locale=pt</code>). With this approach, <code>http://localhost:3000?locale=pt</code> renders the Portuguese localization, while <code>http://localhost:3000?locale=de</code> loads a German localization.</p><p>The locale can be set using one of many different approaches.</p><h4 id="setting-the-locale-from-the-domain-name"><a class="anchorlink" href="#setting-the-locale-from-the-domain-name" data-turbo="false"><span>2.2.1</span> Setting the Locale from the Domain Name</a></h4><p>One option you have is to set the locale from the domain name where your application runs. For example, we want <code>www.example.com</code> to load the English (or default) locale, and <code>www.example.es</code> to load the Spanish locale. Thus the <em>top-level domain name</em> is used for locale setting. This has several advantages:</p> <ul> <li>The locale is an <em>obvious</em> part of the URL.</li> <li>People intuitively grasp in which language the content will be displayed.</li> <li>It is very trivial to implement in Rails.</li> <li>Search engines seem to like that content in different languages lives at different, inter-linked domains.</li> </ul> <p>You can implement it like this in your <code>ApplicationController</code>:</p><div class="interstitial code"> <pre><code class="highlight ruby"><span class="n">around_action</span> <span class="ss">:switch_locale</span> <span class="k">def</span> <span class="nf">switch_locale</span><span class="p">(</span><span class="o">&</span><span class="n">action</span><span class="p">)</span> <span class="n">locale</span> <span class="o">=</span> <span class="n">extract_locale_from_tld</span> <span class="o">||</span> <span class="no">I18n</span><span class="p">.</span><span class="nf">default_locale</span> <span class="no">I18n</span><span class="p">.</span><span class="nf">with_locale</span><span class="p">(</span><span class="n">locale</span><span class="p">,</span> <span class="o">&</span><span class="n">action</span><span class="p">)</span> <span class="k">end</span> <span class="c1"># Get locale from top-level domain or return +nil+ if such locale is not available</span> <span class="c1"># You have to put something like:</span> <span class="c1"># 127.0.0.1 application.com</span> <span class="c1"># 127.0.0.1 application.it</span> <span class="c1"># 127.0.0.1 application.pl</span> <span class="c1"># in your /etc/hosts file to try this out locally</span> <span class="k">def</span> <span class="nf">extract_locale_from_tld</span> <span class="n">parsed_locale</span> <span class="o">=</span> <span class="n">request</span><span class="p">.</span><span class="nf">host</span><span class="p">.</span><span class="nf">split</span><span class="p">(</span><span class="s2">"."</span><span class="p">).</span><span class="nf">last</span> <span class="no">I18n</span><span class="p">.</span><span class="nf">available_locales</span><span class="p">.</span><span class="nf">map</span><span class="p">(</span><span class="o">&</span><span class="ss">:to_s</span><span class="p">).</span><span class="nf">include?</span><span class="p">(</span><span class="n">parsed_locale</span><span class="p">)</span> <span class="p">?</span> <span class="n">parsed_locale</span> <span class="p">:</span> <span class="kp">nil</span> <span class="k">end</span> </code></pre> <button class="clipboard-button" data-clipboard-text="around_action :switch_locale def switch_locale(&action) locale = extract_locale_from_tld || I18n.default_locale I18n.with_locale(locale, &action) end # Get locale from top-level domain or return +nil+ if such locale is not available # You have to put something like: # 127.0.0.1 application.com # 127.0.0.1 application.it # 127.0.0.1 application.pl # in your /etc/hosts file to try this out locally def extract_locale_from_tld parsed_locale = request.host.split(".").last I18n.available_locales.map(&:to_s).include?(parsed_locale) ? parsed_locale : nil end ">Copy</button> </div> <p>We can also set the locale from the <em>subdomain</em> in a very similar way:</p><div class="interstitial code"> <pre><code class="highlight ruby"><span class="c1"># Get locale code from request subdomain (like http://it.application.local:3000)</span> <span class="c1"># You have to put something like:</span> <span class="c1"># 127.0.0.1 it.application.local</span> <span class="c1"># in your /etc/hosts file to try this out locally</span> <span class="c1">#</span> <span class="c1"># Additionally, you need to add the following configuration to your config/environments/development.rb:</span> <span class="c1"># config.hosts << 'it.application.local:3000'</span> <span class="k">def</span> <span class="nf">extract_locale_from_subdomain</span> <span class="n">parsed_locale</span> <span class="o">=</span> <span class="n">request</span><span class="p">.</span><span class="nf">subdomains</span><span class="p">.</span><span class="nf">first</span> <span class="no">I18n</span><span class="p">.</span><span class="nf">available_locales</span><span class="p">.</span><span class="nf">map</span><span class="p">(</span><span class="o">&</span><span class="ss">:to_s</span><span class="p">).</span><span class="nf">include?</span><span class="p">(</span><span class="n">parsed_locale</span><span class="p">)</span> <span class="p">?</span> <span class="n">parsed_locale</span> <span class="p">:</span> <span class="kp">nil</span> <span class="k">end</span> </code></pre> <button class="clipboard-button" data-clipboard-text="# Get locale code from request subdomain (like http://it.application.local:3000) # You have to put something like: # 127.0.0.1 it.application.local # in your /etc/hosts file to try this out locally # # Additionally, you need to add the following configuration to your config/environments/development.rb: # config.hosts << 'it.application.local:3000' def extract_locale_from_subdomain parsed_locale = request.subdomains.first I18n.available_locales.map(&:to_s).include?(parsed_locale) ? parsed_locale : nil end ">Copy</button> </div> <p>If your application includes a locale switching menu, you would then have something like this in it:</p><div class="interstitial code"> <pre><code class="highlight ruby"><span class="n">link_to</span><span class="p">(</span><span class="s2">"Deutsch"</span><span class="p">,</span> <span class="s2">"</span><span class="si">#{</span><span class="no">APP_CONFIG</span><span class="p">[</span><span class="ss">:deutsch_website_url</span><span class="p">]</span><span class="si">}#{</span><span class="n">request</span><span class="p">.</span><span class="nf">env</span><span class="p">[</span><span class="s1">'PATH_INFO'</span><span class="p">]</span><span class="si">}</span><span class="s2">"</span><span class="p">)</span> </code></pre> <button class="clipboard-button" data-clipboard-text="link_to("Deutsch", "#{APP_CONFIG[:deutsch_website_url]}#{request.env['PATH_INFO']}") ">Copy</button> </div> <p>assuming you would set <code>APP_CONFIG[:deutsch_website_url]</code> to some value like <code>http://www.application.de</code>.</p><p>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).</p><h4 id="setting-the-locale-from-url-params"><a class="anchorlink" href="#setting-the-locale-from-url-params" data-turbo="false"><span>2.2.2</span> Setting the Locale from URL Params</a></h4><p>The most usual way of setting (and passing) the locale would be to include it in URL params, as we did in the <code>I18n.with_locale(params[:locale], &action)</code> <em>around_action</em> in the first example. We would like to have URLs like <code>www.example.com/books?locale=ja</code> or <code>www.example.com/ja/books</code> in this case.</p><p>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.</p><p>Getting the locale from <code>params</code> and setting it accordingly is not hard; including it in every URL and thus <strong>passing it through the requests</strong> is. To include an explicit option in every URL, e.g. <code>link_to(books_url(locale: I18n.locale))</code>, would be tedious and probably impossible, of course.</p><p>Rails contains infrastructure for "centralizing dynamic decisions about the URLs" in its <a href="https://api.rubyonrails.org/v8.0.1/classes/ActionDispatch/Routing/Mapper/Base.html#method-i-default_url_options"><code>ApplicationController#default_url_options</code></a>, which is useful precisely in this scenario: it enables us to set "defaults" for <a href="https://api.rubyonrails.org/v8.0.1/classes/ActionDispatch/Routing/UrlFor.html#method-i-url_for"><code>url_for</code></a> and helper methods dependent on it (by implementing/overriding <code>default_url_options</code>).</p><p>We can include something like this in our <code>ApplicationController</code> then:</p><div class="interstitial code"> <pre><code class="highlight ruby"><span class="c1"># app/controllers/application_controller.rb</span> <span class="k">def</span> <span class="nf">default_url_options</span> <span class="p">{</span> <span class="ss">locale: </span><span class="no">I18n</span><span class="p">.</span><span class="nf">locale</span> <span class="p">}</span> <span class="k">end</span> </code></pre> <button class="clipboard-button" data-clipboard-text="def default_url_options { locale: I18n.locale } end ">Copy</button> </div> <p>Every helper method dependent on <code>url_for</code> (e.g. helpers for named routes like <code>root_path</code> or <code>root_url</code>, resource routes like <code>books_path</code> or <code>books_url</code>, etc.) will now <strong>automatically include the locale in the query string</strong>, like this: <code>http://localhost:3001/?locale=ja</code>.</p><p>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.</p><p>You probably want URLs to look like this: <code>http://www.example.com/en/books</code> (which loads the English locale) and <code>http://www.example.com/nl/books</code> (which loads the Dutch locale). This is achievable with the "over-riding <code>default_url_options</code>" strategy from above: you just have to set up your routes with <a href="https://api.rubyonrails.org/v8.0.1/classes/ActionDispatch/Routing/Mapper/Scoping.html"><code>scope</code></a>:</p><div class="interstitial code"> <pre><code class="highlight ruby"><span class="c1"># config/routes.rb</span> <span class="n">scope</span> <span class="s2">"/:locale"</span> <span class="k">do</span> <span class="n">resources</span> <span class="ss">:books</span> <span class="k">end</span> </code></pre> <button class="clipboard-button" data-clipboard-text="scope "/:locale" do resources :books end ">Copy</button> </div> <p>Now, when you call the <code>books_path</code> method you should get <code>"/en/books"</code> (for the default locale). A URL like <code>http://localhost:3001/nl/books</code> should load the Dutch locale, then, and following calls to <code>books_path</code> should return <code>"/nl/books"</code> (because the locale changed).</p><div class="interstitial warning"><p>Since the return value of <code>default_url_options</code> is cached per request, the URLs in a locale selector cannot be generated invoking helpers in a loop that sets the corresponding <code>I18n.locale</code> in each iteration. Instead, leave <code>I18n.locale</code> untouched, and pass an explicit <code>:locale</code> option to the helper, or edit <code>request.original_fullpath</code>.</p></div><p>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:</p><div class="interstitial code"> <pre><code class="highlight ruby"><span class="c1"># config/routes.rb</span> <span class="n">scope</span> <span class="s2">"(:locale)"</span><span class="p">,</span> <span class="ss">locale: </span><span class="sr">/en|nl/</span> <span class="k">do</span> <span class="n">resources</span> <span class="ss">:books</span> <span class="k">end</span> </code></pre> <button class="clipboard-button" data-clipboard-text="scope "(:locale)", locale: /en|nl/ do resources :books end ">Copy</button> </div> <p>With this approach you will not get a <code>Routing Error</code> when accessing your resources such as <code>http://localhost:3001/books</code> without a locale. This is useful for when you want to use the default locale when one is not specified.</p><p>Of course, you need to take special care of the root URL (usually "homepage" or "dashboard") of your application. A URL like <code>http://localhost:3001/nl</code> will not work automatically, because the <code>root to: "dashboard#index"</code> declaration in your <code>routes.rb</code> doesn't take locale into account. (And rightly so: there's only one "root" URL.)</p><p>You would probably need to map URLs like these:</p><div class="interstitial code"> <pre><code class="highlight ruby"><span class="c1"># config/routes.rb</span> <span class="n">get</span> <span class="s2">"/:locale"</span> <span class="o">=></span> <span class="s2">"dashboard#index"</span> </code></pre> <button class="clipboard-button" data-clipboard-text="get "/:locale" => "dashboard#index" ">Copy</button> </div> <p>Do take special care about the <strong>order of your routes</strong>, so this route declaration does not "eat" other ones. (You may want to add it directly before the <code>root :to</code> declaration.)</p><div class="interstitial note"><p>Have a look at various gems which simplify working with routes: <a href="https://github.com/svenfuchs/routing-filter/tree/master">routing_filter</a>, <a href="https://github.com/enriclluelles/route_translator">route_translator</a>.</p></div><h4 id="setting-the-locale-from-user-preferences"><a class="anchorlink" href="#setting-the-locale-from-user-preferences" data-turbo="false"><span>2.2.3</span> Setting the Locale from User Preferences</a></h4><p>An application with authenticated users may allow users to set a locale preference through the application's interface. With this approach, a user's selected locale preference is persisted in the database and used to set the locale for authenticated requests by that user.</p><div class="interstitial code"> <pre><code class="highlight ruby"><span class="n">around_action</span> <span class="ss">:switch_locale</span> <span class="k">def</span> <span class="nf">switch_locale</span><span class="p">(</span><span class="o">&</span><span class="n">action</span><span class="p">)</span> <span class="n">locale</span> <span class="o">=</span> <span class="n">current_user</span><span class="p">.</span><span class="nf">try</span><span class="p">(</span><span class="ss">:locale</span><span class="p">)</span> <span class="o">||</span> <span class="no">I18n</span><span class="p">.</span><span class="nf">default_locale</span> <span class="no">I18n</span><span class="p">.</span><span class="nf">with_locale</span><span class="p">(</span><span class="n">locale</span><span class="p">,</span> <span class="o">&</span><span class="n">action</span><span class="p">)</span> <span class="k">end</span> </code></pre> <button class="clipboard-button" data-clipboard-text="around_action :switch_locale def switch_locale(&action) locale = current_user.try(:locale) || I18n.default_locale I18n.with_locale(locale, &action) end ">Copy</button> </div> <h4 id="choosing-an-implied-locale"><a class="anchorlink" href="#choosing-an-implied-locale" data-turbo="false"><span>2.2.4</span> Choosing an Implied Locale</a></h4><p>When an explicit locale has not been set for a request (e.g. via one of the above methods), an application should attempt to infer the desired locale.</p><h5 id="inferring-locale-from-the-language-header"><a class="anchorlink" href="#inferring-locale-from-the-language-header" data-turbo="false"><span>2.2.4.1</span> Inferring Locale from the Language Header</a></h5><p>The <code>Accept-Language</code> HTTP header indicates the preferred language for request's response. Browsers <a href="https://www.w3.org/International/questions/qa-lang-priorities">set this header value based on the user's language preference settings</a>, making it a good first choice when inferring a locale.</p><p>A trivial implementation of using an <code>Accept-Language</code> header would be:</p><div class="interstitial code"> <pre><code class="highlight ruby"><span class="k">def</span> <span class="nf">switch_locale</span><span class="p">(</span><span class="o">&</span><span class="n">action</span><span class="p">)</span> <span class="n">logger</span><span class="p">.</span><span class="nf">debug</span> <span class="s2">"* Accept-Language: </span><span class="si">#{</span><span class="n">request</span><span class="p">.</span><span class="nf">env</span><span class="p">[</span><span class="s1">'HTTP_ACCEPT_LANGUAGE'</span><span class="p">]</span><span class="si">}</span><span class="s2">"</span> <span class="n">locale</span> <span class="o">=</span> <span class="n">extract_locale_from_accept_language_header</span> <span class="n">logger</span><span class="p">.</span><span class="nf">debug</span> <span class="s2">"* Locale set to '</span><span class="si">#{</span><span class="n">locale</span><span class="si">}</span><span class="s2">'"</span> <span class="no">I18n</span><span class="p">.</span><span class="nf">with_locale</span><span class="p">(</span><span class="n">locale</span><span class="p">,</span> <span class="o">&</span><span class="n">action</span><span class="p">)</span> <span class="k">end</span> <span class="kp">private</span> <span class="k">def</span> <span class="nf">extract_locale_from_accept_language_header</span> <span class="n">request</span><span class="p">.</span><span class="nf">env</span><span class="p">[</span><span class="s2">"HTTP_ACCEPT_LANGUAGE"</span><span class="p">].</span><span class="nf">scan</span><span class="p">(</span><span class="sr">/^[a-z]{2}/</span><span class="p">).</span><span class="nf">first</span> <span class="k">end</span> </code></pre> <button class="clipboard-button" data-clipboard-text="def switch_locale(&action) logger.debug "* Accept-Language: #{request.env['HTTP_ACCEPT_LANGUAGE']}" locale = extract_locale_from_accept_language_header logger.debug "* Locale set to '#{locale}'" I18n.with_locale(locale, &action) end private def extract_locale_from_accept_language_header request.env["HTTP_ACCEPT_LANGUAGE"].scan(/^[a-z]{2}/).first end ">Copy</button> </div> <p>In practice, more robust code is necessary to do this reliably. Iain Hecker's <a href="https://github.com/iain/http_accept_language/tree/master">http_accept_language</a> library or Ryan Tomayko's <a href="https://github.com/rack/rack-contrib/blob/main/lib/rack/contrib/locale.rb">locale</a> Rack middleware provide solutions to this problem.</p><h5 id="inferring-the-locale-from-ip-geolocation"><a class="anchorlink" href="#inferring-the-locale-from-ip-geolocation" data-turbo="false"><span>2.2.4.2</span> Inferring the Locale from IP Geolocation</a></h5><p>The IP address of the client making the request can be used to infer the client's region and thus their locale. Services such as <a href="https://dev.maxmind.com/geoip/geolite2-free-geolocation-data">GeoLite2 Country</a> or gems like <a href="https://github.com/alexreisner/geocoder">geocoder</a> can be used to implement this approach.</p><p>In general, this approach is far less reliable than using the language header and is not recommended for most web applications.</p><h4 id="storing-the-locale-from-the-session-or-cookies"><a class="anchorlink" href="#storing-the-locale-from-the-session-or-cookies" data-turbo="false"><span>2.2.5</span> Storing the Locale from the Session or Cookies</a></h4><div class="interstitial warning"><p>You may be tempted to store the chosen locale in a <em>session</em> or a <em>cookie</em>. However, <strong>do not do this</strong>. 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 <a href="https://en.wikipedia.org/wiki/Representational_State_Transfer"><em>RESTful</em></a>. Read more about the RESTful approach in <a href="https://www.infoq.com/articles/rest-introduction">Stefan Tilkov's articles</a>. Sometimes there are exceptions to this rule and those are discussed below.</p></div><h2 id="internationalization-and-localization"><a class="anchorlink" href="#internationalization-and-localization" data-turbo="false"><span>3</span> Internationalization and Localization</a></h2><p>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.</p><p>Next we need to <em>internationalize</em> our application by abstracting every locale-specific element. Finally, we need to <em>localize</em> it by providing necessary translations for these abstracts.</p><p>Given the following example:</p><div class="interstitial code"> <pre><code class="highlight ruby"><span class="c1"># config/routes.rb</span> <span class="no">Rails</span><span class="p">.</span><span class="nf">application</span><span class="p">.</span><span class="nf">routes</span><span class="p">.</span><span class="nf">draw</span> <span class="k">do</span> <span class="n">root</span> <span class="ss">to: </span><span class="s2">"home#index"</span> <span class="k">end</span> </code></pre> <button class="clipboard-button" data-clipboard-text="Rails.application.routes.draw do root to: "home#index" end ">Copy</button> </div> <div class="interstitial code"> <pre><code class="highlight ruby"><span class="c1"># app/controllers/application_controller.rb</span> <span class="k">class</span> <span class="nc">ApplicationController</span> <span class="o"><</span> <span class="no">ActionController</span><span class="o">::</span><span class="no">Base</span> <span class="n">around_action</span> <span class="ss">:switch_locale</span> <span class="k">def</span> <span class="nf">switch_locale</span><span class="p">(</span><span class="o">&</span><span class="n">action</span><span class="p">)</span> <span class="n">locale</span> <span class="o">=</span> <span class="n">params</span><span class="p">[</span><span class="ss">:locale</span><span class="p">]</span> <span class="o">||</span> <span class="no">I18n</span><span class="p">.</span><span class="nf">default_locale</span> <span class="no">I18n</span><span class="p">.</span><span class="nf">with_locale</span><span class="p">(</span><span class="n">locale</span><span class="p">,</span> <span class="o">&</span><span class="n">action</span><span class="p">)</span> <span class="k">end</span> <span class="k">end</span> </code></pre> <button class="clipboard-button" data-clipboard-text="class ApplicationController < ActionController::Base around_action :switch_locale def switch_locale(&action) locale = params[:locale] || I18n.default_locale I18n.with_locale(locale, &action) end end ">Copy</button> </div> <div class="interstitial code"> <pre><code class="highlight ruby"><span class="c1"># app/controllers/home_controller.rb</span> <span class="k">class</span> <span class="nc">HomeController</span> <span class="o"><</span> <span class="no">ApplicationController</span> <span class="k">def</span> <span class="nf">index</span> <span class="n">flash</span><span class="p">[</span><span class="ss">:notice</span><span class="p">]</span> <span class="o">=</span> <span class="s2">"Hello Flash"</span> <span class="k">end</span> <span class="k">end</span> </code></pre> <button class="clipboard-button" data-clipboard-text="class HomeController < ApplicationController def index flash[:notice] = "Hello Flash" end end ">Copy</button> </div> <div class="interstitial code"> <pre><code class="highlight erb"><span class="c"><!-- app/views/home/index.html.erb --></span> <span class="nt"><h1></span>Hello World<span class="nt"></h1></span> <span class="nt"><p></span><span class="cp"><%=</span> <span class="n">flash</span><span class="p">[</span><span class="ss">:notice</span><span class="p">]</span> <span class="cp">%></span><span class="nt"></p></span> </code></pre> <button class="clipboard-button" data-clipboard-text="<!-- app/views/home/index.html.erb --> <h1>Hello World</h1> <p><%= flash[:notice] %></p> ">Copy</button> </div> <p><img src="images/i18n/demo_untranslated.png" alt="rails i18n demo untranslated"></p><h3 id="abstracting-localized-code"><a class="anchorlink" href="#abstracting-localized-code" data-turbo="false"><span>3.1</span> Abstracting Localized Code</a></h3><p>In our code, there are two strings written in English that will be rendered in our response ("Hello Flash" and "Hello World"). To internationalize this code, these strings need to be replaced by calls to Rails' <code>#t</code> helper with an appropriate key for each string:</p><div class="interstitial code"> <pre><code class="highlight ruby"><span class="c1"># app/controllers/home_controller.rb</span> <span class="k">class</span> <span class="nc">HomeController</span> <span class="o"><</span> <span class="no">ApplicationController</span> <span class="k">def</span> <span class="nf">index</span> <span class="n">flash</span><span class="p">[</span><span class="ss">:notice</span><span class="p">]</span> <span class="o">=</span> <span class="n">t</span><span class="p">(</span><span class="ss">:hello_flash</span><span class="p">)</span> <span class="k">end</span> <span class="k">end</span> </code></pre> <button class="clipboard-button" data-clipboard-text="class HomeController < ApplicationController def index flash[:notice] = t(:hello_flash) end end ">Copy</button> </div> <div class="interstitial code"> <pre><code class="highlight erb"><span class="c"><!-- app/views/home/index.html.erb --></span> <span class="nt"><h1></span><span class="cp"><%=</span> <span class="n">t</span> <span class="ss">:hello_world</span> <span class="cp">%></span><span class="nt"></h1></span> <span class="nt"><p></span><span class="cp"><%=</span> <span class="n">flash</span><span class="p">[</span><span class="ss">:notice</span><span class="p">]</span> <span class="cp">%></span><span class="nt"></p></span> </code></pre> <button class="clipboard-button" data-clipboard-text="<!-- app/views/home/index.html.erb --> <h1><%= t :hello_world %></h1> <p><%= flash[:notice] %></p> ">Copy</button> </div> <p>Now, when this view is rendered, it will show an error message which tells you that the translations for the keys <code>:hello_world</code> and <code>:hello_flash</code> are missing.</p><p><img src="images/i18n/demo_translation_missing.png" alt="rails i18n demo translation missing"></p><div class="interstitial note"><p>Rails adds a <code>t</code> (<code>translate</code>) helper method to your views so that you do not need to spell out <code>I18n.t</code> all the time. Additionally this helper will catch missing translations and wrap the resulting error message into a <code><span class="translation_missing"></code>.</p></div><h3 id="providing-translations-for-internationalized-strings"><a class="anchorlink" href="#providing-translations-for-internationalized-strings" data-turbo="false"><span>3.2</span> Providing Translations for Internationalized Strings</a></h3><p>Add the missing translations into the translation dictionary files:</p><div class="interstitial code"> <pre><code class="highlight yaml"><span class="c1"># config/locales/en.yml</span> <span class="na">en</span><span class="pi">:</span> <span class="na">hello_world</span><span class="pi">:</span> <span class="s">Hello world!</span> <span class="na">hello_flash</span><span class="pi">:</span> <span class="s">Hello flash!</span> </code></pre> <button class="clipboard-button" data-clipboard-text="en: hello_world: Hello world! hello_flash: Hello flash! ">Copy</button> </div> <div class="interstitial code"> <pre><code class="highlight yaml"><span class="c1"># config/locales/pirate.yml</span> <span class="na">pirate</span><span class="pi">:</span> <span class="na">hello_world</span><span class="pi">:</span> <span class="s">Ahoy World</span> <span class="na">hello_flash</span><span class="pi">:</span> <span class="s">Ahoy Flash</span> </code></pre> <button class="clipboard-button" data-clipboard-text="pirate: hello_world: Ahoy World hello_flash: Ahoy Flash ">Copy</button> </div> <p>Because the <code>default_locale</code> hasn't changed, translations use the <code>:en</code> locale and the response renders the english strings:</p><p><img src="images/i18n/demo_translated_en.png" alt="rails i18n demo translated to English"></p><p>If the locale is set via the URL to the pirate locale (<code>http://localhost:3000?locale=pirate</code>), the response renders the pirate strings:</p><p><img src="images/i18n/demo_translated_pirate.png" alt="rails i18n demo translated to pirate"></p><div class="interstitial note"><p>You need to restart the server when you add new locale files.</p></div><p>You may use YAML (<code>.yml</code>) or plain Ruby (<code>.rb</code>) 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.)</p><p>If your translations are stored in YAML files, certain keys must be escaped. They are:</p> <ul> <li>true, on, yes</li> <li>false, off, no</li> </ul> <p>Examples:</p><div class="interstitial code"> <pre><code class="highlight yaml"><span class="c1"># config/locales/en.yml</span> <span class="na">en</span><span class="pi">:</span> <span class="na">success</span><span class="pi">:</span> <span class="s1">'</span><span class="s">true'</span><span class="err">:</span> <span class="s1">'</span><span class="s">True!'</span> <span class="s1">'</span><span class="s">on'</span><span class="err">:</span> <span class="s1">'</span><span class="s">On!'</span> <span class="s1">'</span><span class="s">false'</span><span class="err">:</span> <span class="s1">'</span><span class="s">False!'</span> <span class="na">failure</span><span class="pi">:</span> <span class="na">true</span><span class="pi">:</span> <span class="s1">'</span><span class="s">True!'</span> <span class="na">off</span><span class="pi">:</span> <span class="s1">'</span><span class="s">Off!'</span> <span class="na">false</span><span class="pi">:</span> <span class="s1">'</span><span class="s">False!'</span> </code></pre> <button class="clipboard-button" data-clipboard-text="en: success: 'true': 'True!' 'on': 'On!' 'false': 'False!' failure: true: 'True!' off: 'Off!' false: 'False!' ">Copy</button> </div> <div class="interstitial code"> <pre><code class="highlight ruby"><span class="no">I18n</span><span class="p">.</span><span class="nf">t</span> <span class="s2">"success.true"</span> <span class="c1"># => 'True!'</span> <span class="no">I18n</span><span class="p">.</span><span class="nf">t</span> <span class="s2">"success.on"</span> <span class="c1"># => 'On!'</span> <span class="no">I18n</span><span class="p">.</span><span class="nf">t</span> <span class="s2">"success.false"</span> <span class="c1"># => 'False!'</span> <span class="no">I18n</span><span class="p">.</span><span class="nf">t</span> <span class="s2">"failure.false"</span> <span class="c1"># => Translation Missing</span> <span class="no">I18n</span><span class="p">.</span><span class="nf">t</span> <span class="s2">"failure.off"</span> <span class="c1"># => Translation Missing</span> <span class="no">I18n</span><span class="p">.</span><span class="nf">t</span> <span class="s2">"failure.true"</span> <span class="c1"># => Translation Missing</span> </code></pre> <button class="clipboard-button" data-clipboard-text="I18n.t "success.true" # => 'True!' I18n.t "success.on" # => 'On!' I18n.t "success.false" # => 'False!' I18n.t "failure.false" # => Translation Missing I18n.t "failure.off" # => Translation Missing I18n.t "failure.true" # => Translation Missing ">Copy</button> </div> <h3 id="passing-variables-to-translations"><a class="anchorlink" href="#passing-variables-to-translations" data-turbo="false"><span>3.3</span> Passing Variables to Translations</a></h3><p>One key consideration for successfully internationalizing an application is to avoid making incorrect assumptions about grammar rules when abstracting localized code. Grammar rules that seem fundamental in one locale may not hold true in another one.</p><p>Improper abstraction is shown in the following example, where assumptions are made about the ordering of the different parts of the translation. Note that Rails provides a <code>number_to_currency</code> helper to handle the following case.</p><div class="interstitial code"> <pre><code class="highlight erb"><span class="c"><!-- app/views/products/show.html.erb --></span> <span class="cp"><%=</span> <span class="s2">"</span><span class="si">#{</span><span class="n">t</span><span class="p">(</span><span class="s1">'currency'</span><span class="p">)</span><span class="si">}#{</span><span class="vi">@product</span><span class="p">.</span><span class="nf">price</span><span class="si">}</span><span class="s2">"</span> <span class="cp">%></span> </code></pre> <button class="clipboard-button" data-clipboard-text="<!-- app/views/products/show.html.erb --> <%= "#{t('currency')}#{@product.price}" %> ">Copy</button> </div> <div class="interstitial code"> <pre><code class="highlight yaml"><span class="c1"># config/locales/en.yml</span> <span class="na">en</span><span class="pi">:</span> <span class="na">currency</span><span class="pi">:</span> <span class="s2">"</span><span class="s">$"</span> </code></pre> <button class="clipboard-button" data-clipboard-text="en: currency: "$" ">Copy</button> </div> <div class="interstitial code"> <pre><code class="highlight yaml"><span class="c1"># config/locales/es.yml</span> <span class="na">es</span><span class="pi">:</span> <span class="na">currency</span><span class="pi">:</span> <span class="s2">"</span><span class="s">€"</span> </code></pre> <button class="clipboard-button" data-clipboard-text="es: currency: "€" ">Copy</button> </div> <p>If the product's price is 10 then the proper translation for Spanish is "10 €" instead of "€10" but the abstraction cannot give it.</p><p>To create proper abstraction, the I18n gem ships with a feature called variable interpolation that allows you to use variables in translation definitions and pass the values for these variables to the translation method.</p><p>Proper abstraction is shown in the following example:</p><div class="interstitial code"> <pre><code class="highlight erb"><span class="c"><!-- app/views/products/show.html.erb --></span> <span class="cp"><%=</span> <span class="n">t</span><span class="p">(</span><span class="s1">'product_price'</span><span class="p">,</span> <span class="ss">price: </span><span class="vi">@product</span><span class="p">.</span><span class="nf">price</span><span class="p">)</span> <span class="cp">%></span> </code></pre> <button class="clipboard-button" data-clipboard-text="<!-- app/views/products/show.html.erb --> <%= t('product_price', price: @product.price) %> ">Copy</button> </div> <div class="interstitial code"> <pre><code class="highlight yaml"><span class="c1"># config/locales/en.yml</span> <span class="na">en</span><span class="pi">:</span> <span class="na">product_price</span><span class="pi">:</span> <span class="s2">"</span><span class="s">$%{price}"</span> </code></pre> <button class="clipboard-button" data-clipboard-text="en: product_price: "$%{price}" ">Copy</button> </div> <div class="interstitial code"> <pre><code class="highlight yaml"><span class="c1"># config/locales/es.yml</span> <span class="na">es</span><span class="pi">:</span> <span class="na">product_price</span><span class="pi">:</span> <span class="s2">"</span><span class="s">%{price}</span><span class="nv"> </span><span class="s">€"</span> </code></pre> <button class="clipboard-button" data-clipboard-text="es: product_price: "%{price} €" ">Copy</button> </div> <p>All grammatical and punctuation decisions are made in the definition itself, so the abstraction can give a proper translation.</p><div class="interstitial note"><p>The <code>default</code> and <code>scope</code> keywords are reserved and can't be used as variable names. If used, an <code>I18n::ReservedInterpolationKey</code> exception is raised. If a translation expects an interpolation variable, but this has not been passed to <code>#translate</code>, an <code>I18n::MissingInterpolationArgument</code> exception is raised.</p></div><h3 id="adding-date-time-formats"><a class="anchorlink" href="#adding-date-time-formats" data-turbo="false"><span>3.4</span> Adding Date/Time Formats</a></h3><p>OK! Now let's add a timestamp to the view, so we can demo the <strong>date/time localization</strong> feature as well. To localize the time format you pass the Time object to <code>I18n.l</code> or (preferably) use Rails' <code>#l</code> helper. You can pick a format by passing the <code>:format</code> option - by default the <code>:default</code> format is used.</p><div class="interstitial code"> <pre><code class="highlight erb"><span class="c"><!-- app/views/home/index.html.erb --></span> <span class="nt"><h1></span><span class="cp"><%=</span> <span class="n">t</span> <span class="ss">:hello_world</span> <span class="cp">%></span><span class="nt"></h1></span> <span class="nt"><p></span><span class="cp"><%=</span> <span class="n">flash</span><span class="p">[</span><span class="ss">:notice</span><span class="p">]</span> <span class="cp">%></span><span class="nt"></p></span> <span class="nt"><p></span><span class="cp"><%=</span> <span class="n">l</span> <span class="no">Time</span><span class="p">.</span><span class="nf">now</span><span class="p">,</span> <span class="ss">format: :short</span> <span class="cp">%></span><span class="nt"></p></span> </code></pre> <button class="clipboard-button" data-clipboard-text="<!-- app/views/home/index.html.erb --> <h1><%= t :hello_world %></h1> <p><%= flash[:notice] %></p> <p><%= l Time.now, format: :short %></p> ">Copy</button> </div> <p>And in our pirate translations file let's add a time format (it's already there in Rails' defaults for English):</p><div class="interstitial code"> <pre><code class="highlight yaml"><span class="c1"># config/locales/pirate.yml</span> <span class="na">pirate</span><span class="pi">:</span> <span class="na">time</span><span class="pi">:</span> <span class="na">formats</span><span class="pi">:</span> <span class="na">short</span><span class="pi">:</span> <span class="s2">"</span><span class="s">arrrround</span><span class="nv"> </span><span class="s">%H'ish"</span> </code></pre> <button class="clipboard-button" data-clipboard-text="pirate: time: formats: short: "arrrround %H'ish" ">Copy</button> </div> <p>So that would give you:</p><p><img src="images/i18n/demo_localized_pirate.png" alt="rails i18n demo localized time to pirate"></p><div class="interstitial info"><p>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 <strong>translating Rails' defaults for your locale</strong>. See the <a href="https://github.com/svenfuchs/rails-i18n/tree/master/rails/locale">rails-i18n repository at GitHub</a> for an archive of various locale files. When you put such file(s) in <code>config/locales/</code> directory, they will automatically be ready for use.</p></div><h3 id="inflection-rules-for-other-locales"><a class="anchorlink" href="#inflection-rules-for-other-locales" data-turbo="false"><span>3.5</span> Inflection Rules for Other Locales</a></h3><p>Rails allows you to define inflection rules (such as rules for singularization and pluralization) for locales other than English. In <code>config/initializers/inflections.rb</code>, 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.</p><h3 id="localized-views"><a class="anchorlink" href="#localized-views" data-turbo="false"><span>3.6</span> Localized Views</a></h3><p>Let's say you have a <em>BooksController</em> in your application. Your <em>index</em> action renders content in <code>app/views/books/index.html.erb</code> template. When you put a <em>localized variant</em> of this template: <code>index.es.html.erb</code> in the same directory, Rails will render content in this template, when the locale is set to <code>:es</code>. When the locale is set to the default locale, the generic <code>index.html.erb</code> view will be used. (Future Rails versions may well bring this <em>automagic</em> localization to assets in <code>public</code>, etc.)</p><p>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.</p><h3 id="organization-of-locale-files"><a class="anchorlink" href="#organization-of-locale-files" data-turbo="false"><span>3.7</span> Organization of Locale Files</a></h3><p>When you are using the default SimpleStore shipped with the i18n library, dictionaries are stored in plain-text files on the disk. 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.</p><p>For example, your <code>config/locales</code> directory could look like this:</p><div class="interstitial code"> <pre><code class="highlight plaintext">|-defaults |---es.yml |---en.yml |-models |---book |-----es.yml |-----en.yml |-views |---defaults |-----es.yml |-----en.yml |---books |-----es.yml |-----en.yml |---users |-----es.yml |-----en.yml |---navigation |-----es.yml |-----en.yml </code></pre> <button class="clipboard-button" data-clipboard-text="|-defaults |---es.yml |---en.yml |-models |---book |-----es.yml |-----en.yml |-views |---defaults |-----es.yml |-----en.yml |---books |-----es.yml |-----en.yml |---users |-----es.yml |-----en.yml |---navigation |-----es.yml |-----en.yml ">Copy</button> </div> <p>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.</p><div class="interstitial note"><p>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:</p></div><div class="interstitial code"> <pre><code class="highlight ruby"><span class="c1"># config/application.rb</span> <span class="n">config</span><span class="p">.</span><span class="nf">i18n</span><span class="p">.</span><span class="nf">load_path</span> <span class="o">+=</span> <span class="no">Dir</span><span class="p">[</span><span class="no">Rails</span><span class="p">.</span><span class="nf">root</span><span class="p">.</span><span class="nf">join</span><span class="p">(</span><span class="s2">"config"</span><span class="p">,</span> <span class="s2">"locales"</span><span class="p">,</span> <span class="s2">"**"</span><span class="p">,</span> <span class="s2">"*.{rb,yml}"</span><span class="p">)]</span> </code></pre> <button class="clipboard-button" data-clipboard-text="config.i18n.load_path += Dir[Rails.root.join("config", "locales", "**", "*.{rb,yml}")] ">Copy</button> </div> <h2 id="overview-of-the-i18n-api-features"><a class="anchorlink" href="#overview-of-the-i18n-api-features" data-turbo="false"><span>4</span> Overview of the I18n API Features</a></h2><p>You should have a good understanding of using the i18n library now and know how to internationalize a basic Rails application. In the following chapters, we'll cover its features in more depth.</p><p>These chapters will show examples using both the <code>I18n.translate</code> method as well as the <a href="https://api.rubyonrails.org/v8.0.1/classes/ActionView/Helpers/TranslationHelper.html#method-i-translate"><code>translate</code> view helper method</a> (noting the additional features provided by the view helper method).</p><p>Covered are features like these:</p> <ul> <li>looking up translations</li> <li>interpolating data into translations</li> <li>pluralizing translations</li> <li>using safe HTML translations (view helper method only)</li> <li>localizing dates, numbers, currency, etc.</li> </ul> <h3 id="looking-up-translations"><a class="anchorlink" href="#looking-up-translations" data-turbo="false"><span>4.1</span> Looking up Translations</a></h3><h4 id="basic-lookup-scopes-and-nested-keys"><a class="anchorlink" href="#basic-lookup-scopes-and-nested-keys" data-turbo="false"><span>4.1.1</span> Basic Lookup, Scopes, and Nested Keys</a></h4><p>Translations are looked up by keys which can be both Symbols or Strings, so these calls are equivalent:</p><div class="interstitial code"> <pre><code class="highlight ruby"><span class="no">I18n</span><span class="p">.</span><span class="nf">t</span> <span class="ss">:message</span> <span class="no">I18n</span><span class="p">.</span><span class="nf">t</span> <span class="s2">"message"</span> </code></pre> <button class="clipboard-button" data-clipboard-text="I18n.t :message I18n.t "message" ">Copy</button> </div> <p>The <code>translate</code> method also takes a <code>:scope</code> option which can contain one or more additional keys that will be used to specify a "namespace" or scope for a translation key:</p><div class="interstitial code"> <pre><code class="highlight ruby"><span class="no">I18n</span><span class="p">.</span><span class="nf">t</span> <span class="ss">:record_invalid</span><span class="p">,</span> <span class="ss">scope: </span><span class="p">[</span><span class="ss">:activerecord</span><span class="p">,</span> <span class="ss">:errors</span><span class="p">,</span> <span class="ss">:messages</span><span class="p">]</span> </code></pre> <button class="clipboard-button" data-clipboard-text="I18n.t :record_invalid, scope: [:activerecord, :errors, :messages] ">Copy</button> </div> <p>This looks up the <code>:record_invalid</code> message in the Active Record error messages.</p><p>Additionally, both the key and scopes can be specified as dot-separated keys as in:</p><div class="interstitial code"> <pre><code class="highlight ruby"><span class="no">I18n</span><span class="p">.</span><span class="nf">translate</span> <span class="s2">"activerecord.errors.messages.record_invalid"</span> </code></pre> <button class="clipboard-button" data-clipboard-text="I18n.translate "activerecord.errors.messages.record_invalid" ">Copy</button> </div> <p>Thus the following calls are equivalent:</p><div class="interstitial code"> <pre><code class="highlight ruby"><span class="no">I18n</span><span class="p">.</span><span class="nf">t</span> <span class="s2">"activerecord.errors.messages.record_invalid"</span> <span class="no">I18n</span><span class="p">.</span><span class="nf">t</span> <span class="s2">"errors.messages.record_invalid"</span><span class="p">,</span> <span class="ss">scope: :activerecord</span> <span class="no">I18n</span><span class="p">.</span><span class="nf">t</span> <span class="ss">:record_invalid</span><span class="p">,</span> <span class="ss">scope: </span><span class="s2">"activerecord.errors.messages"</span> <span class="no">I18n</span><span class="p">.</span><span class="nf">t</span> <span class="ss">:record_invalid</span><span class="p">,</span> <span class="ss">scope: </span><span class="p">[</span><span class="ss">:activerecord</span><span class="p">,</span> <span class="ss">:errors</span><span class="p">,</span> <span class="ss">:messages</span><span class="p">]</span> </code></pre> <button class="clipboard-button" data-clipboard-text="I18n.t "activerecord.errors.messages.record_invalid" I18n.t "errors.messages.record_invalid", scope: :activerecord I18n.t :record_invalid, scope: "activerecord.errors.messages" I18n.t :record_invalid, scope: [:activerecord, :errors, :messages] ">Copy</button> </div> <h4 id="defaults"><a class="anchorlink" href="#defaults" data-turbo="false"><span>4.1.2</span> Defaults</a></h4><p>When a <code>:default</code> option is given, its value will be returned if the translation is missing:</p><div class="interstitial code"> <pre><code class="highlight ruby"><span class="no">I18n</span><span class="p">.</span><span class="nf">t</span> <span class="ss">:missing</span><span class="p">,</span> <span class="ss">default: </span><span class="s2">"Not here"</span> <span class="c1"># => 'Not here'</span> </code></pre> <button class="clipboard-button" data-clipboard-text="I18n.t :missing, default: "Not here" # => 'Not here' ">Copy</button> </div> <p>If the <code>:default</code> 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.</p><p>E.g., the following first tries to translate the key <code>:missing</code> and then the key <code>:also_missing.</code> As both do not yield a result, the string "Not here" will be returned:</p><div class="interstitial code"> <pre><code class="highlight ruby"><span class="no">I18n</span><span class="p">.</span><span class="nf">t</span> <span class="ss">:missing</span><span class="p">,</span> <span class="ss">default: </span><span class="p">[</span><span class="ss">:also_missing</span><span class="p">,</span> <span class="s2">"Not here"</span><span class="p">]</span> <span class="c1"># => 'Not here'</span> </code></pre> <button class="clipboard-button" data-clipboard-text="I18n.t :missing, default: [:also_missing, "Not here"] # => 'Not here' ">Copy</button> </div> <h4 id="bulk-and-namespace-lookup"><a class="anchorlink" href="#bulk-and-namespace-lookup" data-turbo="false"><span>4.1.3</span> Bulk and Namespace Lookup</a></h4><p>To look up multiple translations at once, an array of keys can be passed:</p><div class="interstitial code"> <pre><code class="highlight ruby"><span class="no">I18n</span><span class="p">.</span><span class="nf">t</span> <span class="p">[</span><span class="ss">:odd</span><span class="p">,</span> <span class="ss">:even</span><span class="p">],</span> <span class="ss">scope: </span><span class="s2">"errors.messages"</span> <span class="c1"># => ["must be odd", "must be even"]</span> </code></pre> <button class="clipboard-button" data-clipboard-text="I18n.t [:odd, :even], scope: "errors.messages" # => ["must be odd", "must be even"] ">Copy</button> </div> <p>Also, a key can translate to a (potentially nested) hash of grouped translations. E.g., one can receive <em>all</em> Active Record error messages as a Hash with:</p><div class="interstitial code"> <pre><code class="highlight ruby"><span class="no">I18n</span><span class="p">.</span><span class="nf">t</span> <span class="s2">"errors.messages"</span> <span class="c1"># => {:inclusion=>"is not included in the list", :exclusion=> ... }</span> </code></pre> <button class="clipboard-button" data-clipboard-text="I18n.t "errors.messages" # => {:inclusion=>"is not included in the list", :exclusion=> ... } ">Copy</button> </div> <p>If you want to perform interpolation on a bulk hash of translations, you need to pass <code>deep_interpolation: true</code> as a parameter. When you have the following dictionary:</p><div class="interstitial code"> <pre><code class="highlight yaml"><span class="na">en</span><span class="pi">:</span> <span class="na">welcome</span><span class="pi">:</span> <span class="na">title</span><span class="pi">:</span> <span class="s2">"</span><span class="s">Welcome!"</span> <span class="na">content</span><span class="pi">:</span> <span class="s2">"</span><span class="s">Welcome</span><span class="nv"> </span><span class="s">to</span><span class="nv"> </span><span class="s">the</span><span class="nv"> </span><span class="s">%{app_name}"</span> </code></pre> <button class="clipboard-button" data-clipboard-text="en: welcome: title: "Welcome!" content: "Welcome to the %{app_name}" ">Copy</button> </div> <p>then the nested interpolation will be ignored without the setting:</p><div class="interstitial code"> <pre><code class="highlight ruby"><span class="no">I18n</span><span class="p">.</span><span class="nf">t</span> <span class="s2">"welcome"</span><span class="p">,</span> <span class="ss">app_name: </span><span class="s2">"book store"</span> <span class="c1"># => {:title=>"Welcome!", :content=>"Welcome to the %{app_name}"}</span> <span class="no">I18n</span><span class="p">.</span><span class="nf">t</span> <span class="s2">"welcome"</span><span class="p">,</span> <span class="ss">deep_interpolation: </span><span class="kp">true</span><span class="p">,</span> <span class="ss">app_name: </span><span class="s2">"book store"</span> <span class="c1"># => {:title=>"Welcome!", :content=>"Welcome to the book store"}</span> </code></pre> <button class="clipboard-button" data-clipboard-text="I18n.t "welcome", app_name: "book store" # => {:title=>"Welcome!", :content=>"Welcome to the %{app_name}"} I18n.t "welcome", deep_interpolation: true, app_name: "book store" # => {:title=>"Welcome!", :content=>"Welcome to the book store"} ">Copy</button> </div> <h4 id="lazy-lookup"><a class="anchorlink" href="#lazy-lookup" data-turbo="false"><span>4.1.4</span> "Lazy" Lookup</a></h4><p>Rails implements a convenient way to look up the locale inside <em>views</em>. When you have the following dictionary:</p><div class="interstitial code"> <pre><code class="highlight yaml"><span class="na">es</span><span class="pi">:</span> <span class="na">books</span><span class="pi">:</span> <span class="na">index</span><span class="pi">:</span> <span class="na">title</span><span class="pi">:</span> <span class="s2">"</span><span class="s">Título"</span> </code></pre> <button class="clipboard-button" data-clipboard-text="es: books: index: title: "Título" ">Copy</button> </div> <p>you can look up the <code>books.index.title</code> value <strong>inside</strong> <code>app/views/books/index.html.erb</code> template like this (note the dot):</p><div class="interstitial code"> <pre><code class="highlight erb"><span class="cp"><%=</span> <span class="n">t</span> <span class="s1">'.title'</span> <span class="cp">%></span> </code></pre> <button class="clipboard-button" data-clipboard-text="<%= t '.title' %> ">Copy</button> </div> <div class="interstitial note"><p>Automatic translation scoping by partial is only available from the <code>translate</code> view helper method.</p></div><p>"Lazy" lookup can also be used in controllers:</p><div class="interstitial code"> <pre><code class="highlight yaml"><span class="na">en</span><span class="pi">:</span> <span class="na">books</span><span class="pi">:</span> <span class="na">create</span><span class="pi">:</span> <span class="na">success</span><span class="pi">:</span> <span class="s">Book created!</span> </code></pre> <button class="clipboard-button" data-clipboard-text="en: books: create: success: Book created! ">Copy</button> </div> <p>This is useful for setting flash messages for instance:</p><div class="interstitial code"> <pre><code class="highlight ruby"><span class="k">class</span> <span class="nc">BooksController</span> <span class="o"><</span> <span class="no">ApplicationController</span> <span class="k">def</span> <span class="nf">create</span> <span class="c1"># ...</span> <span class="n">redirect_to</span> <span class="n">books_url</span><span class="p">,</span> <span class="ss">notice: </span><span class="n">t</span><span class="p">(</span><span class="s2">".success"</span><span class="p">)</span> <span class="k">end</span> <span class="k">end</span> </code></pre> <button class="clipboard-button" data-clipboard-text="class BooksController < ApplicationController def create # ... redirect_to books_url, notice: t(".success") end end ">Copy</button> </div> <h3 id="pluralization"><a class="anchorlink" href="#pluralization" data-turbo="false"><span>4.2</span> Pluralization</a></h3><p>In many languages — including English — there are only two forms, a singular and a plural, for a given string, e.g. "1 message" and "2 messages". Other languages (<a href="http://www.unicode.org/cldr/charts/latest/supplemental/language_plural_rules.html#ar">Arabic</a>, <a href="http://www.unicode.org/cldr/charts/latest/supplemental/language_plural_rules.html#ja">Japanese</a>, <a href="http://www.unicode.org/cldr/charts/latest/supplemental/language_plural_rules.html#ru">Russian</a> and many more) have different grammars that have additional or fewer <a href="http://cldr.unicode.org/index/cldr-spec/plural-rules">plural forms</a>. Thus, the I18n API provides a flexible pluralization feature.</p><p>The <code>:count</code> 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 in the pluralization backend. By default, only the English pluralization rules are applied.</p><div class="interstitial code"> <pre><code class="highlight ruby"><span class="no">I18n</span><span class="p">.</span><span class="nf">backend</span><span class="p">.</span><span class="nf">store_translations</span> <span class="ss">:en</span><span class="p">,</span> <span class="ss">inbox: </span><span class="p">{</span> <span class="ss">zero: </span><span class="s2">"no messages"</span><span class="p">,</span> <span class="c1"># optional</span> <span class="ss">one: </span><span class="s2">"one message"</span><span class="p">,</span> <span class="ss">other: </span><span class="s2">"%{count} messages"</span> <span class="p">}</span> <span class="no">I18n</span><span class="p">.</span><span class="nf">translate</span> <span class="ss">:inbox</span><span class="p">,</span> <span class="ss">count: </span><span class="mi">2</span> <span class="c1"># => '2 messages'</span> <span class="no">I18n</span><span class="p">.</span><span class="nf">translate</span> <span class="ss">:inbox</span><span class="p">,</span> <span class="ss">count: </span><span class="mi">1</span> <span class="c1"># => 'one message'</span> <span class="no">I18n</span><span class="p">.</span><span class="nf">translate</span> <span class="ss">:inbox</span><span class="p">,</span> <span class="ss">count: </span><span class="mi">0</span> <span class="c1"># => 'no messages'</span> </code></pre> <button class="clipboard-button" data-clipboard-text="I18n.backend.store_translations :en, inbox: { zero: "no messages", # optional one: "one message", other: "%{count} messages" } I18n.translate :inbox, count: 2 # => '2 messages' I18n.translate :inbox, count: 1 # => 'one message' I18n.translate :inbox, count: 0 # => 'no messages' ">Copy</button> </div> <p>The algorithm for pluralizations in <code>:en</code> is as simple as:</p><div class="interstitial code"> <pre><code class="highlight ruby"><span class="n">lookup_key</span> <span class="o">=</span> <span class="ss">:zero</span> <span class="k">if</span> <span class="n">count</span> <span class="o">==</span> <span class="mi">0</span> <span class="o">&&</span> <span class="n">entry</span><span class="p">.</span><span class="nf">has_key?</span><span class="p">(</span><span class="ss">:zero</span><span class="p">)</span> <span class="n">lookup_key</span> <span class="o">||=</span> <span class="n">count</span> <span class="o">==</span> <span class="mi">1</span> <span class="p">?</span> <span class="ss">:one</span> <span class="p">:</span> <span class="ss">:other</span> <span class="n">entry</span><span class="p">[</span><span class="n">lookup_key</span><span class="p">]</span> </code></pre> <button class="clipboard-button" data-clipboard-text="lookup_key = :zero if count == 0 && entry.has_key?(:zero) lookup_key ||= count == 1 ? :one : :other entry[lookup_key] ">Copy</button> </div> <p>The translation denoted as <code>:one</code> is regarded as singular, and the <code>:other</code> is used as plural. If the count is zero, and a <code>:zero</code> entry is present, then it will be used instead of <code>:other</code>.</p><p>If the lookup for the key does not return a Hash suitable for pluralization, an <code>I18n::InvalidPluralizationData</code> exception is raised.</p><h4 id="locale-specific-rules"><a class="anchorlink" href="#locale-specific-rules" data-turbo="false"><span>4.2.1</span> Locale-specific Rules</a></h4><p>The I18n gem provides a Pluralization backend that can be used to enable locale-specific rules. Include it to the Simple backend, then add the localized pluralization algorithms to translation store, as <code>i18n.plural.rule</code>.</p><div class="interstitial code"> <pre><code class="highlight ruby"><span class="no">I18n</span><span class="o">::</span><span class="no">Backend</span><span class="o">::</span><span class="no">Simple</span><span class="p">.</span><span class="nf">include</span><span class="p">(</span><span class="no">I18n</span><span class="o">::</span><span class="no">Backend</span><span class="o">::</span><span class="no">Pluralization</span><span class="p">)</span> <span class="no">I18n</span><span class="p">.</span><span class="nf">backend</span><span class="p">.</span><span class="nf">store_translations</span> <span class="ss">:pt</span><span class="p">,</span> <span class="ss">i18n: </span><span class="p">{</span> <span class="ss">plural: </span><span class="p">{</span> <span class="ss">rule: </span><span class="nb">lambda</span> <span class="p">{</span> <span class="o">|</span><span class="n">n</span><span class="o">|</span> <span class="p">[</span><span class="mi">0</span><span class="p">,</span> <span class="mi">1</span><span class="p">].</span><span class="nf">include?</span><span class="p">(</span><span class="n">n</span><span class="p">)</span> <span class="p">?</span> <span class="ss">:one</span> <span class="p">:</span> <span class="ss">:other</span> <span class="p">}</span> <span class="p">}</span> <span class="p">}</span> <span class="no">I18n</span><span class="p">.</span><span class="nf">backend</span><span class="p">.</span><span class="nf">store_translations</span> <span class="ss">:pt</span><span class="p">,</span> <span class="ss">apples: </span><span class="p">{</span> <span class="ss">one: </span><span class="s2">"one or none"</span><span class="p">,</span> <span class="ss">other: </span><span class="s2">"more than one"</span> <span class="p">}</span> <span class="no">I18n</span><span class="p">.</span><span class="nf">t</span> <span class="ss">:apples</span><span class="p">,</span> <span class="ss">count: </span><span class="mi">0</span><span class="p">,</span> <span class="ss">locale: :pt</span> <span class="c1"># => 'one or none'</span> </code></pre> <button class="clipboard-button" data-clipboard-text="I18n::Backend::Simple.include(I18n::Backend::Pluralization) I18n.backend.store_translations :pt, i18n: { plural: { rule: lambda { |n| [0, 1].include?(n) ? :one : :other } } } I18n.backend.store_translations :pt, apples: { one: "one or none", other: "more than one" } I18n.t :apples, count: 0, locale: :pt # => 'one or none' ">Copy</button> </div> <p>Alternatively, the separate gem <a href="https://github.com/svenfuchs/rails-i18n">rails-i18n</a> can be used to provide a fuller set of locale-specific pluralization rules.</p><h3 id="setting-and-passing-a-locale"><a class="anchorlink" href="#setting-and-passing-a-locale" data-turbo="false"><span>4.3</span> Setting and Passing a Locale</a></h3><p>The locale can be either set pseudo-globally to <code>I18n.locale</code> (which uses <code>Thread.current</code> in the same way as, for example, <code>Time.zone</code>) or can be passed as an option to <code>#translate</code> and <code>#localize</code>.</p><p>If no locale is passed, <code>I18n.locale</code> is used:</p><div class="interstitial code"> <pre><code class="highlight ruby"><span class="no">I18n</span><span class="p">.</span><span class="nf">locale</span> <span class="o">=</span> <span class="ss">:de</span> <span class="no">I18n</span><span class="p">.</span><span class="nf">t</span> <span class="ss">:foo</span> <span class="no">I18n</span><span class="p">.</span><span class="nf">l</span> <span class="no">Time</span><span class="p">.</span><span class="nf">now</span> </code></pre> <button class="clipboard-button" data-clipboard-text="I18n.locale = :de I18n.t :foo I18n.l Time.now ">Copy</button> </div> <p>Explicitly passing a locale:</p><div class="interstitial code"> <pre><code class="highlight ruby"><span class="no">I18n</span><span class="p">.</span><span class="nf">t</span> <span class="ss">:foo</span><span class="p">,</span> <span class="ss">locale: :de</span> <span class="no">I18n</span><span class="p">.</span><span class="nf">l</span> <span class="no">Time</span><span class="p">.</span><span class="nf">now</span><span class="p">,</span> <span class="ss">locale: :de</span> </code></pre> <button class="clipboard-button" data-clipboard-text="I18n.t :foo, locale: :de I18n.l Time.now, locale: :de ">Copy</button> </div> <p>The <code>I18n.locale</code> defaults to <code>I18n.default_locale</code> which defaults to :<code>en</code>. The default locale can be set like this:</p><div class="interstitial code"> <pre><code class="highlight ruby"><span class="no">I18n</span><span class="p">.</span><span class="nf">default_locale</span> <span class="o">=</span> <span class="ss">:de</span> </code></pre> <button class="clipboard-button" data-clipboard-text="I18n.default_locale = :de ">Copy</button> </div> <h3 id="using-safe-html-translations"><a class="anchorlink" href="#using-safe-html-translations" data-turbo="false"><span>4.4</span> Using Safe HTML Translations</a></h3><p>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.</p><div class="interstitial code"> <pre><code class="highlight yaml"><span class="c1"># config/locales/en.yml</span> <span class="na">en</span><span class="pi">:</span> <span class="na">welcome</span><span class="pi">:</span> <span class="s"><b>welcome!</b></span> <span class="na">hello_html</span><span class="pi">:</span> <span class="s"><b>hello!</b></span> <span class="na">title</span><span class="pi">:</span> <span class="na">html</span><span class="pi">:</span> <span class="s"><b>title!</b></span> </code></pre> <button class="clipboard-button" data-clipboard-text="en: welcome: <b>welcome!</b> hello_html: <b>hello!</b> title: html: <b>title!</b> ">Copy</button> </div> <div class="interstitial code"> <pre><code class="highlight erb"><span class="c"><!-- app/views/home/index.html.erb --></span> <span class="nt"><div></span><span class="cp"><%=</span> <span class="n">t</span><span class="p">(</span><span class="s1">'welcome'</span><span class="p">)</span> <span class="cp">%></span><span class="nt"></div></span> <span class="nt"><div></span><span class="cp"><%=</span> <span class="n">raw</span> <span class="n">t</span><span class="p">(</span><span class="s1">'welcome'</span><span class="p">)</span> <span class="cp">%></span><span class="nt"></div></span> <span class="nt"><div></span><span class="cp"><%=</span> <span class="n">t</span><span class="p">(</span><span class="s1">'hello_html'</span><span class="p">)</span> <span class="cp">%></span><span class="nt"></div></span> <span class="nt"><div></span><span class="cp"><%=</span> <span class="n">t</span><span class="p">(</span><span class="s1">'title.html'</span><span class="p">)</span> <span class="cp">%></span><span class="nt"></div></span> </code></pre> <button class="clipboard-button" data-clipboard-text="<!-- app/views/home/index.html.erb --> <div><%= t('welcome') %></div> <div><%= raw t('welcome') %></div> <div><%= t('hello_html') %></div> <div><%= t('title.html') %></div> ">Copy</button> </div> <p>Interpolation escapes as needed though. For example, given:</p><div class="interstitial code"> <pre><code class="highlight yaml"><span class="na">en</span><span class="pi">:</span> <span class="na">welcome_html</span><span class="pi">:</span> <span class="s2">"</span><span class="s"><b>Welcome</span><span class="nv"> </span><span class="s">%{username}!</b>"</span> </code></pre> <button class="clipboard-button" data-clipboard-text="en: welcome_html: "<b>Welcome %{username}!</b>" ">Copy</button> </div> <p>you can safely pass the username as set by the user:</p><div class="interstitial code"> <pre><code class="highlight erb"><span class="c"><%# This is safe, it is going to be escaped if needed. %></span> <span class="cp"><%=</span> <span class="n">t</span><span class="p">(</span><span class="s1">'welcome_html'</span><span class="p">,</span> <span class="ss">username: </span><span class="vi">@current_user</span><span class="p">.</span><span class="nf">username</span><span class="p">)</span> <span class="cp">%></span> </code></pre> <button class="clipboard-button" data-clipboard-text="<%# This is safe, it is going to be escaped if needed. %> <%= t('welcome_html', username: @current_user.username) %> ">Copy</button> </div> <p>Safe strings on the other hand are interpolated verbatim.</p><div class="interstitial note"><p>Automatic conversion to HTML safe translate text is only available from the <code>translate</code> (or <code>t</code>) helper method. This works in views and controllers.</p></div><p><img src="images/i18n/demo_html_safe.png" alt="i18n demo HTML safe"></p><h3 id="translations-for-active-record-models"><a class="anchorlink" href="#translations-for-active-record-models" data-turbo="false"><span>4.5</span> Translations for Active Record Models</a></h3><p>You can use the methods <code>Model.model_name.human</code> and <code>Model.human_attribute_name(attribute)</code> to transparently look up translations for your model and attribute names.</p><p>For example when you add the following translations:</p><div class="interstitial code"> <pre><code class="highlight yaml"><span class="na">en</span><span class="pi">:</span> <span class="na">activerecord</span><span class="pi">:</span> <span class="na">models</span><span class="pi">:</span> <span class="na">user</span><span class="pi">:</span> <span class="s">Customer</span> <span class="na">attributes</span><span class="pi">:</span> <span class="na">user</span><span class="pi">:</span> <span class="na">login</span><span class="pi">:</span> <span class="s2">"</span><span class="s">Handle"</span> <span class="c1"># will translate User attribute "login" as "Handle"</span> </code></pre> <button class="clipboard-button" data-clipboard-text="en: activerecord: models: user: Customer attributes: user: login: "Handle" # will translate User attribute "login" as "Handle" ">Copy</button> </div> <p>Then <code>User.model_name.human</code> will return "Customer" and <code>User.human_attribute_name("login")</code> will return "Handle".</p><p>You can also set a plural form for model names, adding as following:</p><div class="interstitial code"> <pre><code class="highlight yaml"><span class="na">en</span><span class="pi">:</span> <span class="na">activerecord</span><span class="pi">:</span> <span class="na">models</span><span class="pi">:</span> <span class="na">user</span><span class="pi">:</span> <span class="na">one</span><span class="pi">:</span> <span class="s">Customer</span> <span class="na">other</span><span class="pi">:</span> <span class="s">Customers</span> </code></pre> <button class="clipboard-button" data-clipboard-text="en: activerecord: models: user: one: Customer other: Customers ">Copy</button> </div> <p>Then <code>User.model_name.human(count: 2)</code> will return "Customers". With <code>count: 1</code> or without params will return "Customer".</p><p>In the event you need to access nested attributes within a given model, you should nest these under <code>model/attribute</code> at the model level of your translation file:</p><div class="interstitial code"> <pre><code class="highlight yaml"><span class="na">en</span><span class="pi">:</span> <span class="na">activerecord</span><span class="pi">:</span> <span class="na">attributes</span><span class="pi">:</span> <span class="na">user/role</span><span class="pi">:</span> <span class="na">admin</span><span class="pi">:</span> <span class="s2">"</span><span class="s">Admin"</span> <span class="na">contributor</span><span class="pi">:</span> <span class="s2">"</span><span class="s">Contributor"</span> </code></pre> <button class="clipboard-button" data-clipboard-text="en: activerecord: attributes: user/role: admin: "Admin" contributor: "Contributor" ">Copy</button> </div> <p>Then <code>User.human_attribute_name("role.admin")</code> will return "Admin".</p><div class="interstitial note"><p>If you are using a class which includes <code>ActiveModel</code> and does not inherit from <code>ActiveRecord::Base</code>, replace <code>activerecord</code> with <code>activemodel</code> in the above key paths.</p></div><h4 id="error-message-scopes"><a class="anchorlink" href="#error-message-scopes" data-turbo="false"><span>4.5.1</span> Error Message Scopes</a></h4><p>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.</p><p>This gives you quite powerful means to flexibly adjust your messages to your application's needs.</p><p>Consider a User model with a validation for the name attribute like this:</p><div class="interstitial code"> <pre><code class="highlight ruby"><span class="k">class</span> <span class="nc">User</span> <span class="o"><</span> <span class="no">ApplicationRecord</span> <span class="n">validates</span> <span class="ss">:name</span><span class="p">,</span> <span class="ss">presence: </span><span class="kp">true</span> <span class="k">end</span> </code></pre> <button class="clipboard-button" data-clipboard-text="class User < ApplicationRecord validates :name, presence: true end ">Copy</button> </div> <p>The key for the error message in this case is <code>:blank</code>. Thus, in our example it will try the following keys in this order and return the first result:</p><div class="interstitial code"> <pre><code class="highlight plaintext">activerecord.errors.models.user.attributes.name.blank activerecord.errors.models.user.blank activerecord.errors.messages.blank errors.attributes.name.blank errors.messages.blank </code></pre> <button class="clipboard-button" data-clipboard-text="activerecord.errors.models.user.attributes.name.blank activerecord.errors.models.user.blank activerecord.errors.messages.blank errors.attributes.name.blank errors.messages.blank ">Copy</button> </div> <p>To explain it more abstractly, it returns the first key that matches in the order of the following list.</p><div class="interstitial code"> <pre><code class="highlight plaintext">activerecord.errors.models.[model_name].attributes.[attribute_name].[key] activerecord.errors.models.[model_name].[key] activerecord.errors.messages.[key] errors.attributes.[attribute_name].[key] errors.messages.[key] </code></pre> <button class="clipboard-button" data-clipboard-text="activerecord.errors.models.[model_name].attributes.[attribute_name].[key] activerecord.errors.models.[model_name].[key] activerecord.errors.messages.[key] errors.attributes.[attribute_name].[key] errors.messages.[key] ">Copy</button> </div> <p>When your models are additionally using inheritance then the messages are looked up in the inheritance chain.</p><p>For example, you might have an Admin model inheriting from User:</p><div class="interstitial code"> <pre><code class="highlight ruby"><span class="k">class</span> <span class="nc">Admin</span> <span class="o"><</span> <span class="no">User</span> <span class="n">validates</span> <span class="ss">:name</span><span class="p">,</span> <span class="ss">presence: </span><span class="kp">true</span> <span class="k">end</span> </code></pre> <button class="clipboard-button" data-clipboard-text="class Admin < User validates :name, presence: true end ">Copy</button> </div> <p>Then Active Record will look for messages in this order:</p><div class="interstitial code"> <pre><code class="highlight ruby"><span class="n">activerecord</span><span class="p">.</span><span class="nf">errors</span><span class="p">.</span><span class="nf">models</span><span class="p">.</span><span class="nf">admin</span><span class="p">.</span><span class="nf">attributes</span><span class="p">.</span><span class="nf">name</span><span class="p">.</span><span class="nf">blank</span> <span class="n">activerecord</span><span class="p">.</span><span class="nf">errors</span><span class="p">.</span><span class="nf">models</span><span class="p">.</span><span class="nf">admin</span><span class="p">.</span><span class="nf">blank</span> <span class="n">activerecord</span><span class="p">.</span><span class="nf">errors</span><span class="p">.</span><span class="nf">models</span><span class="p">.</span><span class="nf">user</span><span class="p">.</span><span class="nf">attributes</span><span class="p">.</span><span class="nf">name</span><span class="p">.</span><span class="nf">blank</span> <span class="n">activerecord</span><span class="p">.</span><span class="nf">errors</span><span class="p">.</span><span class="nf">models</span><span class="p">.</span><span class="nf">user</span><span class="p">.</span><span class="nf">blank</span> <span class="n">activerecord</span><span class="p">.</span><span class="nf">errors</span><span class="p">.</span><span class="nf">messages</span><span class="p">.</span><span class="nf">blank</span> <span class="n">errors</span><span class="p">.</span><span class="nf">attributes</span><span class="p">.</span><span class="nf">name</span><span class="p">.</span><span class="nf">blank</span> <span class="n">errors</span><span class="p">.</span><span class="nf">messages</span><span class="p">.</span><span class="nf">blank</span> </code></pre> <button class="clipboard-button" data-clipboard-text="activerecord.errors.models.admin.attributes.name.blank activerecord.errors.models.admin.blank activerecord.errors.models.user.attributes.name.blank activerecord.errors.models.user.blank activerecord.errors.messages.blank errors.attributes.name.blank errors.messages.blank ">Copy</button> </div> <p>This way you can provide special translations for various error messages at different points in your model's inheritance chain and in the attributes, models, or default scopes.</p><h4 id="error-message-interpolation"><a class="anchorlink" href="#error-message-interpolation" data-turbo="false"><span>4.5.2</span> Error Message Interpolation</a></h4><p>The translated model name, translated attribute name, and value are always available for interpolation as <code>model</code>, <code>attribute</code> and <code>value</code> respectively.</p><p>So, for example, instead of the default error message <code>"cannot be blank"</code> you could use the attribute name like this : <code>"Please fill in your %{attribute}"</code>.</p> <ul> <li><code>count</code>, where available, can be used for pluralization if present:</li> </ul> <div class="table-wrapper"><table><thead> <tr> <th>validation</th> <th>with option</th> <th>message</th> <th>interpolation</th> </tr> </thead><tbody> <tr> <td>confirmation</td> <td>-</td> <td>:confirmation</td> <td>attribute</td> </tr> <tr> <td>acceptance</td> <td>-</td> <td>:accepted</td> <td>-</td> </tr> <tr> <td>presence</td> <td>-</td> <td>:blank</td> <td>-</td> </tr> <tr> <td>absence</td> <td>-</td> <td>:present</td> <td>-</td> </tr> <tr> <td>length</td> <td>:within, :in</td> <td>:too_short</td> <td>count</td> </tr> <tr> <td>length</td> <td>:within, :in</td> <td>:too_long</td> <td>count</td> </tr> <tr> <td>length</td> <td>:is</td> <td>:wrong_length</td> <td>count</td> </tr> <tr> <td>length</td> <td>:minimum</td> <td>:too_short</td> <td>count</td> </tr> <tr> <td>length</td> <td>:maximum</td> <td>:too_long</td> <td>count</td> </tr> <tr> <td>uniqueness</td> <td>-</td> <td>:taken</td> <td>-</td> </tr> <tr> <td>format</td> <td>-</td> <td>:invalid</td> <td>-</td> </tr> <tr> <td>inclusion</td> <td>-</td> <td>:inclusion</td> <td>-</td> </tr> <tr> <td>exclusion</td> <td>-</td> <td>:exclusion</td> <td>-</td> </tr> <tr> <td>associated</td> <td>-</td> <td>:invalid</td> <td>-</td> </tr> <tr> <td>non-optional association</td> <td>-</td> <td>:required</td> <td>-</td> </tr> <tr> <td>numericality</td> <td>-</td> <td>:not_a_number</td> <td>-</td> </tr> <tr> <td>numericality</td> <td>:greater_than</td> <td>:greater_than</td> <td>count</td> </tr> <tr> <td>numericality</td> <td>:greater_than_or_equal_to</td> <td>:greater_than_or_equal_to</td> <td>count</td> </tr> <tr> <td>numericality</td> <td>:equal_to</td> <td>:equal_to</td> <td>count</td> </tr> <tr> <td>numericality</td> <td>:less_than</td> <td>:less_than</td> <td>count</td> </tr> <tr> <td>numericality</td> <td>:less_than_or_equal_to</td> <td>:less_than_or_equal_to</td> <td>count</td> </tr> <tr> <td>numericality</td> <td>:other_than</td> <td>:other_than</td> <td>count</td> </tr> <tr> <td>numericality</td> <td>:only_integer</td> <td>:not_an_integer</td> <td>-</td> </tr> <tr> <td>numericality</td> <td>:in</td> <td>:in</td> <td>count</td> </tr> <tr> <td>numericality</td> <td>:odd</td> <td>:odd</td> <td>-</td> </tr> <tr> <td>numericality</td> <td>:even</td> <td>:even</td> <td>-</td> </tr> <tr> <td>comparison</td> <td>:greater_than</td> <td>:greater_than</td> <td>count</td> </tr> <tr> <td>comparison</td> <td>:greater_than_or_equal_to</td> <td>:greater_than_or_equal_to</td> <td>count</td> </tr> <tr> <td>comparison</td> <td>:equal_to</td> <td>:equal_to</td> <td>count</td> </tr> <tr> <td>comparison</td> <td>:less_than</td> <td>:less_than</td> <td>count</td> </tr> <tr> <td>comparison</td> <td>:less_than_or_equal_to</td> <td>:less_than_or_equal_to</td> <td>count</td> </tr> <tr> <td>comparison</td> <td>:other_than</td> <td>:other_than</td> <td>count</td> </tr> </tbody></table></div> <h3 id="translations-for-action-mailer-e-mail-subjects"><a class="anchorlink" href="#translations-for-action-mailer-e-mail-subjects" data-turbo="false"><span>4.6</span> Translations for Action Mailer E-Mail Subjects</a></h3><p>If you don't pass a subject to the <code>mail</code> method, Action Mailer will try to find it in your translations. The performed lookup will use the pattern <code><mailer_scope>.<action_name>.subject</code> to construct the key.</p><div class="interstitial code"> <pre><code class="highlight ruby"><span class="c1"># user_mailer.rb</span> <span class="k">class</span> <span class="nc">UserMailer</span> <span class="o"><</span> <span class="no">ActionMailer</span><span class="o">::</span><span class="no">Base</span> <span class="k">def</span> <span class="nf">welcome</span><span class="p">(</span><span class="n">user</span><span class="p">)</span> <span class="c1">#...</span> <span class="k">end</span> <span class="k">end</span> </code></pre> <button class="clipboard-button" data-clipboard-text="# user_mailer.rb class UserMailer < ActionMailer::Base def welcome(user) #... end end ">Copy</button> </div> <div class="interstitial code"> <pre><code class="highlight yaml"><span class="na">en</span><span class="pi">:</span> <span class="na">user_mailer</span><span class="pi">:</span> <span class="na">welcome</span><span class="pi">:</span> <span class="na">subject</span><span class="pi">:</span> <span class="s2">"</span><span class="s">Welcome</span><span class="nv"> </span><span class="s">to</span><span class="nv"> </span><span class="s">Rails</span><span class="nv"> </span><span class="s">Guides!"</span> </code></pre> <button class="clipboard-button" data-clipboard-text="en: user_mailer: welcome: subject: "Welcome to Rails Guides!" ">Copy</button> </div> <p>To send parameters to interpolation use the <code>default_i18n_subject</code> method on the mailer.</p><div class="interstitial code"> <pre><code class="highlight ruby"><span class="c1"># user_mailer.rb</span> <span class="k">class</span> <span class="nc">UserMailer</span> <span class="o"><</span> <span class="no">ActionMailer</span><span class="o">::</span><span class="no">Base</span> <span class="k">def</span> <span class="nf">welcome</span><span class="p">(</span><span class="n">user</span><span class="p">)</span> <span class="n">mail</span><span class="p">(</span><span class="ss">to: </span><span class="n">user</span><span class="p">.</span><span class="nf">email</span><span class="p">,</span> <span class="ss">subject: </span><span class="n">default_i18n_subject</span><span class="p">(</span><span class="ss">user: </span><span class="n">user</span><span class="p">.</span><span class="nf">name</span><span class="p">))</span> <span class="k">end</span> <span class="k">end</span> </code></pre> <button class="clipboard-button" data-clipboard-text="# user_mailer.rb class UserMailer < ActionMailer::Base def welcome(user) mail(to: user.email, subject: default_i18n_subject(user: user.name)) end end ">Copy</button> </div> <div class="interstitial code"> <pre><code class="highlight yaml"><span class="na">en</span><span class="pi">:</span> <span class="na">user_mailer</span><span class="pi">:</span> <span class="na">welcome</span><span class="pi">:</span> <span class="na">subject</span><span class="pi">:</span> <span class="s2">"</span><span class="s">%{user},</span><span class="nv"> </span><span class="s">welcome</span><span class="nv"> </span><span class="s">to</span><span class="nv"> </span><span class="s">Rails</span><span class="nv"> </span><span class="s">Guides!"</span> </code></pre> <button class="clipboard-button" data-clipboard-text="en: user_mailer: welcome: subject: "%{user}, welcome to Rails Guides!" ">Copy</button> </div> <h3 id="overview-of-other-built-in-methods-that-provide-i18n-support"><a class="anchorlink" href="#overview-of-other-built-in-methods-that-provide-i18n-support" data-turbo="false"><span>4.7</span> Overview of Other Built-In Methods that Provide I18n Support</a></h3><p>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.</p><h4 id="action-view-helper-methods"><a class="anchorlink" href="#action-view-helper-methods" data-turbo="false"><span>4.7.1</span> Action View Helper Methods</a></h4> <ul> <li><p><code>distance_of_time_in_words</code> translates and pluralizes its result and interpolates the number of seconds, minutes, hours, and so on. See <a href="https://github.com/rails/rails/blob/main/actionview/lib/action_view/locale/en.yml#L4">datetime.distance_in_words</a> translations.</p></li> <li><p><code>datetime_select</code> and <code>select_month</code> use translated month names for populating the resulting select tag. See <a href="https://github.com/rails/rails/blob/main/activesupport/lib/active_support/locale/en.yml#L15">date.month_names</a> for translations. <code>datetime_select</code> also looks up the order option from <a href="https://github.com/rails/rails/blob/main/activesupport/lib/active_support/locale/en.yml#L18">date.order</a> (unless you pass the option explicitly). All date selection helpers translate the prompt using the translations in the <a href="https://github.com/rails/rails/blob/main/actionview/lib/action_view/locale/en.yml#L39">datetime.prompts</a> scope if applicable.</p></li> <li><p>The <code>number_to_currency</code>, <code>number_with_precision</code>, <code>number_to_percentage</code>, <code>number_with_delimiter</code>, and <code>number_to_human_size</code> helpers use the number format settings located in the <a href="https://github.com/rails/rails/blob/main/activesupport/lib/active_support/locale/en.yml#L37">number</a> scope.</p></li> </ul> <h4 id="active-model-methods"><a class="anchorlink" href="#active-model-methods" data-turbo="false"><span>4.7.2</span> Active Model Methods</a></h4> <ul> <li><p><code>model_name.human</code> and <code>human_attribute_name</code> use translations for model names and attribute names if available in the <a href="https://github.com/rails/rails/blob/main/activerecord/lib/active_record/locale/en.yml#L36">activerecord.models</a> scope. They also support translations for inherited class names (e.g. for use with STI) as explained above in "Error message scopes".</p></li> <li><p><code>ActiveModel::Errors#generate_message</code> (which is used by Active Model validations but may also be used manually) uses <code>model_name.human</code> and <code>human_attribute_name</code> (see above). It also translates the error message and supports translations for inherited class names as explained above in "Error message scopes".</p></li> <li><p><code>ActiveModel::Error#full_message</code> and <code>ActiveModel::Errors#full_messages</code> prepend the attribute name to the error message using a format looked up from <code>errors.format</code> (default: <a href="https://github.com/rails/rails/blob/main/activemodel/lib/active_model/locale/en.yml#L4"><code>"%{attribute} %{message}"</code></a>). To customize the default format, override it in the app's locale files. To customize the format per model or per attribute, see <a href="configuring.html#config-active-model-i18n-customize-full-message"><code>config.active_model.i18n_customize_full_message</code></a>.</p></li> </ul> <h4 id="active-support-methods"><a class="anchorlink" href="#active-support-methods" data-turbo="false"><span>4.7.3</span> Active Support Methods</a></h4> <ul> <li><code>Array#to_sentence</code> uses format settings as given in the <a href="https://github.com/rails/rails/blob/main/activesupport/lib/active_support/locale/en.yml#L33">support.array</a> scope.</li> </ul> <h2 id="how-to-store-your-custom-translations"><a class="anchorlink" href="#how-to-store-your-custom-translations" data-turbo="false"><span>5</span> How to Store your Custom Translations</a></h2><p>The Simple backend shipped with Active Support allows you to store translations in both plain Ruby and YAML format.<sup class="footnote" id="footnote-2-ref"><a href="#footnote-2">2</a></sup></p><p>For example a Ruby Hash providing translations can look like this:</p><div class="interstitial code"> <pre><code class="highlight ruby"><span class="p">{</span> <span class="ss">pt: </span><span class="p">{</span> <span class="ss">foo: </span><span class="p">{</span> <span class="ss">bar: </span><span class="s2">"baz"</span> <span class="p">}</span> <span class="p">}</span> <span class="p">}</span> </code></pre> <button class="clipboard-button" data-clipboard-text="{ pt: { foo: { bar: "baz" } } } ">Copy</button> </div> <p>The equivalent YAML file would look like this:</p><div class="interstitial code"> <pre><code class="highlight yaml"><span class="na">pt</span><span class="pi">:</span> <span class="na">foo</span><span class="pi">:</span> <span class="na">bar</span><span class="pi">:</span> <span class="s">baz</span> </code></pre> <button class="clipboard-button" data-clipboard-text="pt: foo: bar: baz ">Copy</button> </div> <p>As you see, in both cases the top level key is the locale. <code>:foo</code> is a namespace key and <code>:bar</code> is the key for the translation "baz".</p><p>Here is a "real" example from the Active Support <code>en.yml</code> translations YAML file:</p><div class="interstitial code"> <pre><code class="highlight yaml"><span class="na">en</span><span class="pi">:</span> <span class="na">date</span><span class="pi">:</span> <span class="na">formats</span><span class="pi">:</span> <span class="na">default</span><span class="pi">:</span> <span class="s2">"</span><span class="s">%Y-%m-%d"</span> <span class="na">short</span><span class="pi">:</span> <span class="s2">"</span><span class="s">%b</span><span class="nv"> </span><span class="s">%d"</span> <span class="na">long</span><span class="pi">:</span> <span class="s2">"</span><span class="s">%B</span><span class="nv"> </span><span class="s">%d,</span><span class="nv"> </span><span class="s">%Y"</span> </code></pre> <button class="clipboard-button" data-clipboard-text="en: date: formats: default: "%Y-%m-%d" short: "%b %d" long: "%B %d, %Y" ">Copy</button> </div> <p>So, all of the following equivalent lookups will return the <code>:short</code> date format <code>"%b %d"</code>:</p><div class="interstitial code"> <pre><code class="highlight ruby"><span class="no">I18n</span><span class="p">.</span><span class="nf">t</span> <span class="s2">"date.formats.short"</span> <span class="no">I18n</span><span class="p">.</span><span class="nf">t</span> <span class="s2">"formats.short"</span><span class="p">,</span> <span class="ss">scope: :date</span> <span class="no">I18n</span><span class="p">.</span><span class="nf">t</span> <span class="ss">:short</span><span class="p">,</span> <span class="ss">scope: </span><span class="s2">"date.formats"</span> <span class="no">I18n</span><span class="p">.</span><span class="nf">t</span> <span class="ss">:short</span><span class="p">,</span> <span class="ss">scope: </span><span class="p">[</span><span class="ss">:date</span><span class="p">,</span> <span class="ss">:formats</span><span class="p">]</span> </code></pre> <button class="clipboard-button" data-clipboard-text="I18n.t "date.formats.short" I18n.t "formats.short", scope: :date I18n.t :short, scope: "date.formats" I18n.t :short, scope: [:date, :formats] ">Copy</button> </div> <p>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.</p><h2 id="customize-your-i18n-setup"><a class="anchorlink" href="#customize-your-i18n-setup" data-turbo="false"><span>6</span> Customize Your I18n Setup</a></h2><h3 id="using-different-backends"><a class="anchorlink" href="#using-different-backends" data-turbo="false"><span>6.1</span> Using Different Backends</a></h3><p>For several reasons the Simple backend shipped with Active Support only does the "simplest thing that could possibly work" <em>for Ruby on Rails</em><sup class="footnote" id="footnote-3-ref"><a href="#footnote-3">3</a></sup> ... 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.</p><p>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, by passing a backend instance to the <code>I18n.backend=</code> setter.</p><p>For example, you can replace the Simple backend with 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.</p><p>With the Chain backend, you could use the Active Record backend and fall back to the (default) Simple backend:</p><div class="interstitial code"> <pre><code class="highlight ruby"><span class="no">I18n</span><span class="p">.</span><span class="nf">backend</span> <span class="o">=</span> <span class="no">I18n</span><span class="o">::</span><span class="no">Backend</span><span class="o">::</span><span class="no">Chain</span><span class="p">.</span><span class="nf">new</span><span class="p">(</span><span class="no">I18n</span><span class="o">::</span><span class="no">Backend</span><span class="o">::</span><span class="no">ActiveRecord</span><span class="p">.</span><span class="nf">new</span><span class="p">,</span> <span class="no">I18n</span><span class="p">.</span><span class="nf">backend</span><span class="p">)</span> </code></pre> <button class="clipboard-button" data-clipboard-text="I18n.backend = I18n::Backend::Chain.new(I18n::Backend::ActiveRecord.new, I18n.backend) ">Copy</button> </div> <h3 id="using-different-exception-handlers"><a class="anchorlink" href="#using-different-exception-handlers" data-turbo="false"><span>6.2</span> Using Different Exception Handlers</a></h3><p>The I18n API defines the following exceptions that will be raised by backends when the corresponding unexpected conditions occur:</p> <div class="table-wrapper"><table><thead> <tr> <th>Exception</th> <th>Reason</th> </tr> </thead><tbody> <tr> <td><code>I18n::MissingTranslationData</code></td> <td>no translation was found for the requested key</td> </tr> <tr> <td><code>I18n::InvalidLocale</code></td> <td>the locale set to <code>I18n.locale</code> is invalid (e.g. <code>nil</code>)</td> </tr> <tr> <td><code>I18n::InvalidPluralizationData</code></td> <td>a count option was passed but the translation data is not suitable for pluralization</td> </tr> <tr> <td><code>I18n::MissingInterpolationArgument</code></td> <td>the translation expects an interpolation argument that has not been passed</td> </tr> <tr> <td><code>I18n::ReservedInterpolationKey</code></td> <td>the translation contains a reserved interpolation variable name (i.e. one of: <code>scope</code>, <code>default</code>)</td> </tr> <tr> <td><code>I18n::UnknownFileType</code></td> <td>the backend does not know how to handle a file type that was added to <code>I18n.load_path</code></td> </tr> </tbody></table></div> <h4 id="customizing-how-i18n-missingtranslationdata-is-handled"><a class="anchorlink" href="#customizing-how-i18n-missingtranslationdata-is-handled" data-turbo="false"><span>6.2.1</span> Customizing how <code>I18n::MissingTranslationData</code> is handled</a></h4><p>If <code>config.i18n.raise_on_missing_translations</code> is <code>true</code>, <code>I18n::MissingTranslationData</code> errors will be raised from views and controllers. If the value is <code>:strict</code>, models also raise the error. It's a good idea to turn this on in your test environment, so you can catch places where missing translations are requested.</p><p>If <code>config.i18n.raise_on_missing_translations</code> is <code>false</code> (the default in all environments), the exception's error message will be printed. This contains the missing key/scope so you can fix your code.</p><p>If you want to customize this behaviour further, you should set <code>config.i18n.raise_on_missing_translations = false</code> and then implement a <code>I18n.exception_handler</code>. The custom exception handler can be a proc or a class with a <code>call</code> method:</p><div class="interstitial code"> <pre><code class="highlight ruby"><span class="c1"># config/initializers/i18n.rb</span> <span class="k">module</span> <span class="nn">I18n</span> <span class="k">class</span> <span class="nc">RaiseExceptForSpecificKeyExceptionHandler</span> <span class="k">def</span> <span class="nf">call</span><span class="p">(</span><span class="n">exception</span><span class="p">,</span> <span class="n">locale</span><span class="p">,</span> <span class="n">key</span><span class="p">,</span> <span class="n">options</span><span class="p">)</span> <span class="k">if</span> <span class="n">key</span> <span class="o">==</span> <span class="s2">"special.key"</span> <span class="s2">"translation missing!"</span> <span class="c1"># return this, don't raise it</span> <span class="k">elsif</span> <span class="n">exception</span><span class="p">.</span><span class="nf">is_a?</span><span class="p">(</span><span class="no">MissingTranslation</span><span class="p">)</span> <span class="k">raise</span> <span class="n">exception</span><span class="p">.</span><span class="nf">to_exception</span> <span class="k">else</span> <span class="k">raise</span> <span class="n">exception</span> <span class="k">end</span> <span class="k">end</span> <span class="k">end</span> <span class="k">end</span> <span class="no">I18n</span><span class="p">.</span><span class="nf">exception_handler</span> <span class="o">=</span> <span class="no">I18n</span><span class="o">::</span><span class="no">RaiseExceptForSpecificKeyExceptionHandler</span><span class="p">.</span><span class="nf">new</span> </code></pre> <button class="clipboard-button" data-clipboard-text="module I18n class RaiseExceptForSpecificKeyExceptionHandler def call(exception, locale, key, options) if key == "special.key" "translation missing!" # return this, don't raise it elsif exception.is_a?(MissingTranslation) raise exception.to_exception else raise exception end end end end I18n.exception_handler = I18n::RaiseExceptForSpecificKeyExceptionHandler.new ">Copy</button> </div> <p>This would raise all exceptions the same way the default handler would, except in the case of <code>I18n.t("special.key")</code>.</p><h2 id="translating-model-content"><a class="anchorlink" href="#translating-model-content" data-turbo="false"><span>7</span> Translating Model Content</a></h2><p>The I18n API described in this guide is primarily intended for translating interface strings. If you are looking to translate model content (e.g. blog posts), you will need a different solution to help with this.</p><p>Several gems can help with this:</p> <ul> <li><a href="https://github.com/shioyama/mobility">Mobility</a>: Provides support for storing translations in many formats, including translation tables, JSON columns (PostgreSQL), etc.</li> <li><a href="https://github.com/barsoom/traco">Traco</a>: Translatable columns stored in the model table itself</li> </ul> <h2 id="conclusion"><a class="anchorlink" href="#conclusion" data-turbo="false"><span>8</span> Conclusion</a></h2><p>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.</p><h2 id="contributing-to-rails-i18n"><a class="anchorlink" href="#contributing-to-rails-i18n" data-turbo="false"><span>9</span> Contributing to Rails I18n</a></h2><p>I18n support in Ruby on Rails was introduced in the release 2.2 and is still evolving. The project follows the good Ruby on Rails development tradition of evolving solutions in gems and real applications first, and only then cherry-picking the best-of-breed of most widely useful features for inclusion in the core.</p><p>Thus we encourage everybody to experiment with new ideas and features in gems or other libraries and make them available to the community. (Don't forget to announce your work on our <a href="https://groups.google.com/forum/#!forum/rails-i18n">mailing list</a>!)</p><p>If you find your own locale (language) missing from our <a href="https://github.com/svenfuchs/rails-i18n/tree/master/rails/locale">example translations data</a> repository for Ruby on Rails, please <a href="https://github.com/guides/fork-a-project-and-submit-your-modifications"><em>fork</em></a> the repository, add your data, and send a <a href="https://help.github.com/articles/about-pull-requests/">pull request</a>.</p><h2 id="resources"><a class="anchorlink" href="#resources" data-turbo="false"><span>10</span> Resources</a></h2> <ul> <li><a href="https://github.com/svenfuchs/rails-i18n">GitHub: rails-i18n</a> - Code repository and issue tracker for the rails-i18n project. Most importantly you can find lots of <a href="https://github.com/svenfuchs/rails-i18n/tree/master/rails/locale">example translations</a> for Rails that should work for your application in most cases.</li> <li><a href="https://github.com/ruby-i18n/i18n">GitHub: i18n</a> - Code repository and issue tracker for the i18n gem.</li> </ul> <h2 id="authors"><a class="anchorlink" href="#authors" data-turbo="false"><span>11</span> Authors</a></h2> <ul> <li><a href="http://svenfuchs.com">Sven Fuchs</a> (initial author)</li> <li><a href="http://www.karmi.cz">Karel Minařík</a></li> </ul> <h2 id="footnotes"><a class="anchorlink" href="#footnotes" data-turbo="false"><span>12</span> Footnotes</a></h2><p class="footnote" id="footnote-1"><a href="#footnote-1-ref"><sup>1</sup></a> Or, to quote <a href="https://en.wikipedia.org/wiki/Internationalization_and_localization">Wikipedia</a>: <em>"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."</em></p><p class="footnote" id="footnote-2"><a href="#footnote-2-ref"><sup>2</sup></a> Other backends might allow or require to use other formats, e.g. a GetText backend might allow to read GetText files.</p><p class="footnote" id="footnote-3"><a href="#footnote-3-ref"><sup>3</sup></a> 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.</p> </section> <hr> <footer aria-labelledby="heading-feedback" role="region"> <h2 id="heading-feedback">Feedback</h2> <p> You're encouraged to help improve the quality of this guide. </p> <p> Please contribute if you see any typos or factual errors. To get started, you can read our <a href="https://edgeguides.rubyonrails.org/contributing_to_ruby_on_rails.html#contributing-to-the-rails-documentation">documentation contributions</a> section. </p> <p> You may also find incomplete content or stuff that is not up to date. Please do add any missing documentation for main. Make sure to check <a href="https://edgeguides.rubyonrails.org">Edge Guides</a> first to verify if the issues are already fixed or not on the main branch. Check the <a href="ruby_on_rails_guides_guidelines.html">Ruby on Rails Guides Guidelines</a> for style and conventions. </p> <p> If for whatever reason you spot something to fix but cannot patch it yourself, please <a href="https://github.com/rails/rails/issues">open an issue</a>. </p> <p>And last but not least, any kind of discussion regarding Ruby on Rails documentation is very welcome on the <a href="https://discuss.rubyonrails.org/c/rubyonrails-docs">official Ruby on Rails Forum</a>. </p> </footer> </div> </article> </main> <hr class="hide" /> <footer id="complementary"> <div class="wrapper"> <p>This work is licensed under a <a href="https://creativecommons.org/licenses/by-sa/4.0/">Creative Commons Attribution-ShareAlike 4.0 International</a> License</p> <p>"Rails", "Ruby on Rails", and the Rails logo are trademarks of David Heinemeier Hansson. All rights reserved.</p> </div> </footer> <a href="#main-skip-link" class="back-to-top" data-turbo="false"><span class="visibly-hidden">Back to top</span></a> </body> </html>