Skip to content
Menu
Railshero
  • Blog
  • About Me
  • Contact Me
  • Privacy Policy
Railshero
railshero.pw Internationalization in Rails

Internationalization in Rails

Posted on June 28, 2023June 30, 2023 by Rails Hero

As the digital world entwines itself around us, the need to communicate efficiently across borders has become paramount. Software developers now, more than ever, find themselves needing to transcend language and cultural barriers. The concept of internationalization (often abbreviated as i18n) becomes crucial at this juncture. For those working with Rails, you’re in a sweet spot. Rails comes equipped with a simple, yet efficient mechanism to manage i18n in your applications. Let’s dissect how Rails handles internationalization.

What is Internationalization?

Internationalization lies at the heart of making your application accessible and user-friendly across diverse languages, locales, and cultures. This might involve tasks such as translating text, managing diverse date and time formats, handling multiple currencies, and accommodating varying number formats.

Internationalization goes hand in hand with localization (l10n) — the process of tweaking an application to cater to a particular locale or market. We’ll be focusing on the Rails I18n API here, a handy framework for translating your application and managing locale-specific settings.

Setting up Internationalization in Rails

Before delving into the particulars of Rails’ i18n API, let’s first establish a rudimentary Rails application as an example. This article assumes that you’re already familiar with creating a Rails application.

rails new i18n_demo
cd i18n_demo

Configuring the Locale

Setting up internationalization kicks off with the configuration of the locale. A locale represents a set of user preferences including language, country, and any specific variances the user prefers in their user interface. Locale configuration can be handled in different ways such as in the application configuration, per request, or in the user’s profile stored in the database.

Default Locale

By default, Rails uses the English language (:en) as the locale. Should you need to switch this default locale, you can do so in the config/application.rb file:

config.i18n.default_locale = :de # for German language

Available Locales

You can specify the locales available in your application using the config.i18n.available_locales configuration:

config.i18n.available_locales = [:en, :de]

This line makes only English and German available in your application. An attempt to set the locale to something else will cause an I18n::InvalidLocale exception.

Setting up Translation Files

To store the translations of your strings, you will use YAML files. These files will be stored in the config/locales directory.

For example, you may have a file config/locales/en.yml for English translations:

en:
hello: "Hello world"

And a config/locales/de.yml file for German translations:

de:
hello: "Hallo Welt"

In these files, ‘en’ and ‘de’ are the top-level keys that represent the locale. The key-value pairs underneath each locale are the translations. You can organize these files in a way that makes sense for your application.

Using Translations

Once your translation files are set up, you can use the t (or translate) helper method in your views to display the translated strings:

<%= t 'hello' %>

If your application is set to the English locale, this line will display “Hello world”. If it’s set to the German locale, it will display “Hallo Welt”.

Organizing Translation Files

As your application expands, managing your translation files may become more challenging. For better organization, you can structure your translations into “scopes”.

For instance, your English translation file might look like this:

en:
users:
show:
welcome: "Welcome, %{username}!"

In your German translation file, it might look like this:

de:
users:
show:
welcome: "Willkommen, %{username}!"

Then, in your view, you could use this translation like this:

<%= t 'users.show.welcome', username: @user.username %>

Pluralization

Rails also supports pluralization out of the box. This is done using the pluralize method in combination with the t method.

In your translation file, you can define pluralized strings like this:

en:
inbox:
one: "You have 1 new message"
other: "You have %{count} new messages"

Then, in your view, you can use the translation like this:

<%= t('inbox', count: @messages.count) %>

Formatting Dates and Times

In addition to translating strings, Rails assists you in formatting dates and times based on the locale. Rails uses the strftime format for this purpose. You can define your date and time formats in your translation files:

en:
date:
formats:
short: "%b %d"
time:
formats:
short: "%H:%M"

Then, in your views, you can use these formats like this:

<%= l @post.created_at, format: :short %>

The l (or localize) method is similar to the t method, but it is used for localizing dates and times.

Locale in the URL

One common pattern in internationalized applications is to include the locale in the URL of each page. This can be done by setting the locale in a before_action in your ApplicationController and including the locale in your routes.

class ApplicationController < ActionController::Base
before_action :set_locale

def set_locale
I18n.locale = params[:locale] || I18n.default_locale
end

def default_url_options
{ locale: I18n.locale }
end
end

In your config/routes.rb, you can include the locale like this:

scope "/:locale", locale: /#{I18n.available_locales.join("|")}/ do
# your routes go here...
end

With these changes, your URLs will look something like http://localhost:3000/en/posts for English and http://localhost:3000/de/posts for German.

Fallbacks

In cases where a translation is unavailable for every string in every language, Rails can “fallback” to another locale. This can be established in your config/application.rb file:

config.i18n.fallbacks = [:en]

In this example, if a translation is not available in the current locale, Rails will fall back to the English locale.

Wrapping Up

This article merely touches the surface of setting up internationalization in a Rails application. There’s a plethora of advanced i18n features, like custom translation backends and locale-specific routing, to explore. But the tools and concepts we’ve discussed here provide a sturdy base for internationalizing a Rails application.

As the world gets smaller and technology continues to blur the lines between people and cultures, internationalization has become increasingly important. By offering your application in multiple languages, you can engage a global audience and deliver a superior user experience. Thanks to Rails’ robust and adaptable I18n API, achieving this has never been simpler.

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Tags

active record active storage assets assign to many associations attachment attachments authentication authorization avatar bootstrap cdn config database deploy deployments devise DRY environment variables file uploads Gemfile gems has_many helpers heroku index indexing initializer javascript pagination parameters postgres production public routes.rb ruby gem ruby gems search sendgrid server smtp stylesheets variants views voting

Recent Posts

  • Understanding the DRY Principle in Rails
  • Building Multi-tenant Applications with Rails
  • Rails Basics: Templating Engines
  • Deploying With Capistrano
  • Automated Testing in Rails

Archives

  • July 2023
  • June 2023
  • October 2021
  • September 2021
  • August 2021
  • July 2021

Categories

  • Active Record
  • Activity Logging
  • Apps
  • Assets
  • Attachments
  • Audio
  • Authentication
  • Authorization
  • Deployments
  • Error Pages
  • File Uploads
  • General
  • Heroku
  • Heroku
  • Pagination
  • Rails Basics
  • RubyGems
  • Search Engine Optimization
  • Search/Indexing
  • Testing
  • User Interface
  • Video
  • Views & Templating
  • Voting
  • Web Security
©2025 Railshero | Theme: Wordly by SuperbThemes
We use cookies on our website to give you the most relevant experience by remembering your preferences and repeat visits. By clicking “Accept All”, you consent to the use of ALL the cookies. However, you may visit "Cookie Settings" to provide a controlled consent.
Cookie SettingsAccept All
Manage consent

Privacy Overview

This website uses cookies to improve your experience while you navigate through the website. Out of these, the cookies that are categorized as necessary are stored on your browser as they are essential for the working of basic functionalities of the website. We also use third-party cookies that help us analyze and understand how you use this website. These cookies will be stored in your browser only with your consent. You also have the option to opt-out of these cookies. But opting out of some of these cookies may affect your browsing experience.
Necessary
Always Enabled
Necessary cookies are absolutely essential for the website to function properly. This category only includes cookies that ensures basic functionalities and security features of the website. These cookies do not store any personal information.
Non-necessary
Any cookies that may not be particularly necessary for the website to function and is used specifically to collect user personal data via analytics, ads, other embedded contents are termed as non-necessary cookies. It is mandatory to procure user consent prior to running these cookies on your website.
SAVE & ACCEPT