How to i18n in Ruby on Rails

1. Create config/initializers/i18n.rb file

#encoding: utf-8
I18n.default_locale = :en
LANGUAGES = [
'en' ],
['English' ,
["Español".html_safe, 'es' ]
]

2. In config/routes.rb

  scope '(:locale)' do
    root 'main#index'
    resources :news
  end

3. Add following lines in app/controllers/application_controller.rb

class ApplicationController < ActionController::Base
  # Prevent CSRF attacks by raising an exception.
  # For APIs, you may want to use :null_session instead.

  before_filter :set_i18n_locale_from_params
  protect_from_forgery with: :exception

    def set_i18n_locale_from_params
        if params[:locale]
            if I18n.available_locales.include?(params[:locale].to_sym)
                I18n.locale = params[:locale]
            else
                flash.now[:notice] = "#{params[:locale]} translation not available"
                logger.error flash.now[:notice]
            end
        end
    end

    def default_url_options
        { :locale => I18n.locale }
    end
end


4. in app/views/application.html.erb

<%= @page_title || t('.title') %>

5. in config/locales/en.yml and es.yml ...

en:
  hello: "Hello world"

Comments