
Rails i18n: Panduan Lengkap Internasionalisasi Ruby on Rails
Dari file locale pertama hingga produksi: konfigurasikan Rails I18n, gunakan pembantu t(), tangani bentuk jamak CLDR, perbaiki masalah umum, dan tambahkan rantai fallback locale cerdas.
Pahami Arsitektur I18n Rails
Rails dilengkapi gem I18n bawaan. File terjemahan berada di config/locales/ sebagai file YAML (default) atau Ruby. Framework menyediakan pembantu t() (alias untuk I18n.translate) dalam tampilan, controller, model, dan mailer. Rails I18n dirancang sederhana — langsung menangani terjemahan dasar, interpolasi, dan bentuk jamak.
# Rails includes i18n out of the box via the i18n gem
# config/application.rb
module MyApp
class Application < Rails::Application
# Default locale
config.i18n.default_locale = :en
# Available locales
config.i18n.available_locales = [:en, :de, :ja, :es, :fr, :'pt-BR']
# Fallback to default locale when translation is missing
config.i18n.fallbacks = true
# Load translations from nested directories
config.i18n.load_path += Dir[Rails.root.join('config', 'locales', '**', '*.{rb,yml}')]
end
end# config/routes.rb
Rails.application.routes.draw do
scope "/:locale", locale: /en|de|ja|es|fr|pt-BR/ do
root "home#index"
resources :products
end
root "home#index"
end
# app/controllers/application_controller.rb
class ApplicationController < ActionController::Base
around_action :switch_locale
private
def switch_locale(&action)
locale = params[:locale] || I18n.default_locale
I18n.with_locale(locale, &action)
end
def default_url_options
{ locale: I18n.locale }
end
endKonfigurasikan Pengaturan Locale
Atur default_locale, available_locales, dan perilaku fallback dalam config/application.rb atau initializer. Konfigurasikan deteksi locale dalam ApplicationController Anda menggunakan before_action untuk menetapkan locale dari URL, sesi, cookie, atau header Accept-Language.
# config/locales/en.yml
en:
nav:
home: "Home"
about: "About"
settings: "Settings"
greeting: "Hello, %{name}!"
cart:
item_count:
one: "%{count} item"
other: "%{count} items"
# config/locales/de.yml
de:
nav:
home: "Startseite"
about: "Über uns"
settings: "Einstellungen"
greeting: "Hallo, %{name}!"
cart:
item_count:
one: "%{count} Artikel"
other: "%{count} Artikel"Gunakan Pembantu t()
Pembantu t() tersedia di seluruh Rails — tampilan, controller, model, mailer, dan job. Pembantu ini menerima kunci, variabel interpolasi opsional, serta opsi seperti nilai default dan cakupan. Dalam tampilan, Rails mendukung pencarian lambat yang secara otomatis membatasi kunci ke controller dan action saat ini.
# In views (ERB)
<h1><%= t('nav.home') %></h1>
<p><%= t('greeting', name: @user.name) %></p>
# In controllers
flash[:notice] = t('flash.product_created')
# In models
validates :name, presence: { message: I18n.t('errors.blank') }
# With HTML (safe)
<%= t('terms_html', link: link_to(t('terms_link'), '/terms')) %>Tangani Bentuk Jamak
Rails I18n menggunakan kategori bentuk jamak CLDR: zero, one, two, few, many, other. Bahasa Inggris hanya memerlukan one dan other, tetapi bahasa lain memerlukan lebih banyak bentuk. Tentukan terjemahan bentuk jamak sebagai kunci YAML bersarang di bawah kategori jumlah yang diperlukan bahasa target Anda.
# In YAML:
en:
cart:
item_count:
zero: "No items"
one: "%{count} item"
other: "%{count} items"
# Arabic (6 forms):
ar:
cart:
item_count:
zero: "لا عناصر"
one: "عنصر واحد"
two: "عنصران"
few: "%{count} عناصر"
many: "%{count} عنصرًا"
other: "%{count} عنصر"
# Usage in views:
<%= t('cart.item_count', count: @cart.items.size) %>Tambahkan Rantai Fallback Locale
I18n.fallbacks bawaan Rails hanya menyediakan fallback dasar dari locale regional ke default. Pengguna pt-BR dengan kunci yang tidak tersedia melihat bahasa Inggris alih-alih pt-PT. rails-locale-chain menambahkan rantai penggabungan mendalam yang dapat dikonfigurasi agar pengguna regional selalu melihat terjemahan tersedia yang paling dekat.
# Lazy lookups use the controller/action as scope
# app/views/products/index.html.erb
# Instead of t('products.index.title'), just use:
<h1><%= t('.title') %></h1>
<p><%= t('.description') %></p>
# Rails looks up: products.index.title and products.index.description
# config/locales/en.yml
en:
products:
index:
title: "All Products"
description: "Browse our catalog"Otomatiskan Penerjemahan
Setelah penyiapan Rails I18n selesai, terjemahkan file locale YAML Anda menggunakan AI. i18n Agent mendukung YAML secara native — arahkan ke file locale sumber dan alat ini menghasilkan semua bahasa target dengan mempertahankan kunci bersarang, variabel interpolasi, dan bentuk jamak.
# Gemfile
gem 'rails-locale-chain'
# config/initializers/locale_chain.rb
Rails.application.config.i18n.fallbacks = {
'pt-BR': ['pt', 'en'],
'zh-Hant-TW': ['zh-Hant', 'zh', 'en'],
'es-419': ['es', 'en'],
}
# The gem deep-merges translations across the chain
# pt-BR -> pt -> en
# Missing keys in pt-BR are filled from pt, then enKesalahan Umum
Kesalahan InvalidPluralizationData
Pencarian Lambat di Luar Tampilan
Kesalahan Sintaks YAML Merusak Semua Terjemahan
Coba i18n Agent Sekarang
Lepaskan file terjemahan Anda di sini
JSON, YAML, PO, XML, CSV, Markdown, Properties
atau klik untuk menjelajahi
Bahasa target