Available_locales

This is a method to load available translations and put them in a Hash. Locale files should have a key named “this_file_language:” which contains, as a value, the current language that supports.

Uses each_with_object method, available on edge.

application_controller.rb

class ApplicationController < ActionController::Base

  before_filter :set_locale

  private

  # Sets the locale for the current request.
  def set_locale
    # I18n.default_locale returns the current default locale. Defaults to 'en-US'
    locale = params[:locale] || session[:locale] || (this_user.site_language if is_logged_in?) || I18n.default_locale
    locale = AVAILABLE_LOCALES.keys.include?(locale) ? locale : I18n.default_locale
    session[:locale] = I18n.locale = locale
  end

end

config/initializers/locales.rb

LOCALES_DIRECTORY = "#{RAILS_ROOT}/config/locales/" 
AVAILABLE_LOCALES =
Dir.new(LOCALES_DIRECTORY).entries.collect do |x|
  x =~ /\.yml/ ? x.sub(/\.yml/,"") : nil
end.compact.each_with_object({}) do |str, hsh|
  hsh[str] = YAML.load_file(LOCALES_DIRECTORY + str + ".yml")[str]["this_file_language"]
end.freeze # {"it-IT" => "Italiano", "en-US" => "American English"}

it-IT.yml example

  switch_language: "Cambia lingua" 
  this_file_language: "Italiano" 

en-US.yml example

  switch_language: "Switch language" 
  this_file_language: "American English" 

helper

  # Shows language selection.
  def language_selection
    r = []
    AVAILABLE_LOCALES.each do |language_code, language|
      r << link_to_unless(I18n.locale == language_code, language, params.merge(:locale => language_code)) + "&nbsp;" 
    end
    r
  end

Loading all translations, useful for production.

# This goes in the same locales.rb initializer.
Dir.glob("#{LOCALES_DIRECTORY}*.yml").each do |file|
  I18n.load_translations file
end

revision: 8 last updated: September 08, 2008 21:03 by: Sven