Skip to content

Instantly share code, notes, and snippets.

@ryenski
Created October 1, 2024 17:46
Show Gist options
  • Save ryenski/7ec7cc1d43d96e0c9355ee9083b9b21b to your computer and use it in GitHub Desktop.
Save ryenski/7ec7cc1d43d96e0c9355ee9083b9b21b to your computer and use it in GitHub Desktop.
I18n Best Practices in Rails

I18n Best Practices

Use human-readable keys

Prefer natural language over abstracted strings for language keys. This helps to make the views easier to read and understand.

Take advantage of the fact that spaces are legal in YAML keys:

Examples

# Bad
t('.all_label')

# Good
t('.All Workspaces')
# Bad
en:
  labels:
    all_label: All Data Rooms

# Good
en:
  labels:
    All Workspaces: All Data Rooms

On the other hand don't be too wordy. It's not always necessary or desirable to use the entire string as the key.

Examples

# Bad
en:
  labels:
    You are using too many resources to switch to this plan.: "You are using too many resources to switch to this plan."

# Good
en:
  labels:
    Too many resources: "You are using too many resources to switch to this plan."

Use Safe HTML translations

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. Ref: Rails Internationalization (I18n) API — Ruby on Rails Guides

Examples

en:
  welcome: <b>welcome!</b>
  hello_html: <b>hello!</b>
  title:
    html: <b>title!</b>

Place generic strings under the root

Some generic strings can be reused everywhere. These should be placed under the root and referenced without lazy lookup.

Examples

# Bad
# app/views/workspaces/index.html.erb
t('.Workspaces')

# Good
t('Workspaces)
# Bad
en:
  Workspaces:
    index: 
      title: Data Rooms

# Good
en:
  Workspaces: Data Rooms

Use lazy lookup

Rails implements a convenient way to look up the locale inside views.

Examples

en:
  workspaces:
    index:
      title: "Data Rooms"

you can look up the books.index.title value inside app/views/books/index.html.erb template like this (note the dot):

<%= t '.title' %>

Use ActiveRecord attribute names

Many places where it can be tempting to use lazy lookup keys, it is better to use ActiveRecord attributes instead.

Examples

# Bad
en:
  workspaces:
    form:
      name: Data Room Name

# Good
en:
  activerecord:
    attributes:
      workspace:
        name: Data Room Name

Use sensible defaults

Examples

# Bad

# Good

Avoid embedded translations

Examples

# Bad



# Good
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment