
Rails i18n: Ruby on Rails 국제화 완벽 가이드
첫 로케일 파일부터 프로덕션까지, Rails I18n을 설정하고 t() 도우미를 사용하며 CLDR 복수형을 처리하고 흔한 문제를 해결한 뒤 스마트 로케일 폴백 체인을 추가해 보세요.
Rails I18n 아키텍처 이해
Rails에는 I18n gem이 내장되어 있어요. 번역 파일은 config/locales/에 YAML(기본값) 또는 Ruby 파일로 저장돼요. 프레임워크는 뷰, 컨트롤러, 모델, 메일러에서 t() 도우미(I18n.translate의 별칭)를 제공해요. Rails I18n은 의도적으로 단순하게 설계되어 기본 번역, 보간, 복수형을 바로 처리해요.
# 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
end로케일 설정 구성
config/application.rb 또는 초기화 파일에서 default_locale, available_locales, 폴백 동작을 설정하세요. ApplicationController에서 before_action을 사용해 URL, 세션, 쿠키 또는 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"t() 도우미 사용
t() 도우미는 뷰, 컨트롤러, 모델, 메일러, 작업 등 Rails 어디에서나 사용할 수 있어요. 키, 선택 사항인 보간 변수, 기본값이나 범위 같은 옵션을 받아요. 뷰에서는 현재 컨트롤러와 작업을 기준으로 키 범위를 자동 지정하는 지연 조회를 지원해요.
# 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')) %>복수형 처리
Rails I18n은 zero, one, two, few, many, other라는 CLDR 복수형 범주를 사용해요. 영어에는 one과 other만 필요하지만 다른 언어에는 더 많은 형식이 필요해요. 대상 언어에 필요한 count 범주 아래에 복수형 번역을 중첩 YAML 키로 정의하세요.
# 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) %>로케일 폴백 체인 추가
Rails의 내장 I18n.fallbacks는 지역 로케일에서 기본 로케일로 넘어가는 기본 폴백만 제공해요. pt-BR 사용자는 키가 누락되면 pt-PT 대신 영어를 보게 돼요. rails-locale-chain은 설정 가능한 딥 머지 체인을 추가해 지역 사용자가 가장 가까운 번역을 볼 수 있게 해요.
# 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"번역 자동화
Rails I18n 설정이 끝나면 AI로 YAML 로케일 파일을 번역하세요. i18n Agent는 YAML을 기본으로 지원해요. 원본 로케일 파일을 지정하면 중첩 키, 보간 변수, 복수형을 보존하면서 모든 대상 언어 파일을 생성해요.
# 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 en흔한 실수
InvalidPluralizationData 오류
뷰 밖에서 지연 조회 사용
모든 번역을 망가뜨리는 YAML 구문 오류
지금 i18n Agent 사용해 보기
번역 파일을 여기에 드롭
JSON, YAML, PO, XML, CSV, Markdown, Properties
또는 클릭하여 파일 선택
대상 언어