views:

21

answers:

1

I am creating a little website which is currently being translated into different languages. I use Rails' out-of-the-box translation: l18n. To change the localization, a parameter called locale must be given, e.g.: http://localhost:3000/?locale=nl.

In ApplicationController this parameter is saved into a session variable and used as localization. How can I check if the locale actually exists? Are there any built in functions, or do I need to add an exists: "true" to every localization file to check it?

A: 

Rails will default to "en" as the default locale in case if a locale doesn't exist. So to be nasty if I pass http://localhost:3000/?locale=de and that translation doesn't exist, 'en' will be used.

Have a look here http://guides.rubyonrails.org/i18n.html , especially the section "2.3 Setting and Passing the Locale"

#config/initializers/available_locales.rb 

# Get loaded locales conveniently 

module I18n 
 class << self  
  def available_locales; backend.available_locales; end  
 end  
 module Backend 
   class Simple 
     def available_locales; translations.keys.collect { |l| l.to_s }.sort; end  
   end  
 end 
end 

# You need to "force-initialize" loaded locales 
I18n.backend.send(:init_translations) 

AVAILABLE_LOCALES = I18n.backend.available_locales 
RAILS_DEFAULT_LOGGER.debug "* Loaded locales: #{AVAILABLE_LOCALES.inspect}" 

You can then wrap the constant for easy access in ApplicationController:

class ApplicationController < ActionController::Base 
  def available_locales; AVAILABLE_LOCALES; end 
end 

You can implement it like this in your ApplicationController:

before_filter :set_locale 

def set_locale 
  I18n.locale = extract_locale_from_params 
end 

def extract_locale_from_params 
  parsed_locale = params[:locale] 
 (available_locales.include? parsed_locale) ? parsed_locale : nil 
end  

HTH

Anand