before_filter :set_locale def set_locale # if params[:locale] is nil then I18n.default_locale will be used I18n.locale = params[:locale] end
# app/controllers/application_controller.rb def default_url_options(options = {}) logger.debug “default_url_options is passed options: #{options.inspect}n” {:locale => I18n.locale} end
# config/routes.rb map.resources :books, :path_prefix => '/:locale' # => www.example.com/nl/books map.root '/:locale', :controller => “dashboard”
before_filter :set_locale def set_locale I18n.locale = extract_locale_from_uri end
def extract_locale_from_tld parsed_locale = request.host.split('.').last I18n.available_locales.include? (parsed_locale.to_sym) ? parsed_locale : nil end
def set_locale logger.debug = “* Accept-Language: #{request.env['HTTP_ACCEPT_LANGUAGE']}” I18n.locale = extract_locale_from_accept_language_header end
def extract_locale_from_accept_language_header request.env['HTTP_ACCEPT_LANGUAGE'].scan(/^[a-z] {2}/).first end
en: activerecord: models: user: foo admin: bar attributes: user: login: “Handle” # => will translate User attribute “login” as “Handle”
en: activerecord: errors: messages: blank: “can not has nottin” # => u = User.new # => #<User id:nil, etc> # => u.valid? # => false # => u.errors.on(:name) # => “can not has nottin”
en: activerecord: errors: messages: already_registered: “u already is {{model}}” # => u.errors.on(:email) # => “u already is foo”
en: activerecord: errors: template: header: one: “1 error prohibted this {{model}} from being saved” other: “{{count}} errors prohibted this {{model}} from being saved” body: “There were problems with the following fields:”
i18n i18n i18n backend backend core_ext helpers locales exceptions gettext gettext helpers tag fallbacks locale version
backend Interpolation fast simple active_record active_record compiler Interpolation gettext base compiler missing Interpolation helpers cache compiler store_procs Interpolation Interpolation cascader compiler compiler Interpolation links translation chain compiler Interpolation metadata cldr compiler Interpolation pluralization fallbacks compiler
def default_locale(locale) @@default_locale = locale.to_sym rescue nil end
def backend @@backend ||= Backend::Simple.new end
module I18n module Backend class Simple include Base end end end
def available_locales @@available_locales ||= backend.available_locales end
def default_exception_handler(exception, locale, key, options) return exception.message if MissingTranslationData === exception raise exception end
def config Thread.current[:i18n_config] ||= I18n::Config.new end
I18n.t :invalid, :scope => [:active_record, :error_messages] # => I18n.translation :invalid :active_record.error_messa ges.invalid
I18n.t :foo, :bar => 'baz' #=> 'foo baz' I18n.t :foo, :count => 1 #=> 'foo' I18n.t :foo, :count => 0 #=> 'foos' I18n.t :foo, :count => 2 #=> 'foos' I18n.t :foo, :default => 'bar'
def translate(&args) options = args.pop if args.last.is_a?(Hash) key = args.shift locale = options && options.delete(:locale) || config.locale raises = options && options.delete(:raise) config.backend.translate(locale, key, options || {}) rescue I18n::ArgumentError => exception raise exception if raises handle_exception(exception, locale, key, options) end alias :t :translate
def localize(object, options = {}) locale = options.delete(:locale) || config.locale format = options.delete(:format) || :default config.backend.localize(locale, object, format, options) end alias :l :localize
def load_translations(*filenames) filenames.each { |filename| load_file(filename) } end
def load_file(filename) type = File.extname(filename).tr('.', '').downcase raise UnknownFileType.new(type, filename) unless respond_to?(:”load_#(type)”) data = send(:”load_#(type)”, filename) data.each { |locale, d| merge_translation(locale, d) } end
def store_translations(locale, data, options = {}) merge_translations(locale, data, options) end
def merge_translations(locale, data, options = {}) locale = locale.to_sym translations[locale] ||= {} separator = options[:separator] || I18n.default_separator data = unwind_keys(data, separator) data = deep_symbolized_keys(data) merger = proc do |key, v1, v2| Hash === v1 && Hash === v2 ? v1.merge(v2, &merger) : (v2 || v1) end translations[locale].merge!(data, &merger) end
def translate(locale, key, options = {}) raise InvalidLocale.new(locale) unless locale return key.map { |k| translate(locale, k, options) } if key.is_a?(Array) if options.empty? entry = resolve(locale, key, lookup(locale, key), options) raise(I18n::MissingTranslationData.new(locale, key, options)) if entry.nil?
else count, scope, default = options.values_at(:count, :scope, :default) values = options.reject { |name, value| RESERVED_KEYS.include?(name) } entry = lookup(locale, key, scope, options) entry = entry.nil? && default ? default(locale, key, default, options) : resolve(locale, key, entry, options)
raise(I18n::MissingTranslationData.new(locale, key, options)) if entry.nil? entry = pluralize(locale, entry, count) if count entry = interpolate(locale, entry, values) if values end entry end
case match when '%a' then I18n.t(:"date.abbr_day_names”, :locale => locale, :format => format)[object.wday] when '%A' then I18n.t(:"date.day_names”, :locale => locale, :format => format)[object.wday] when '%b' then I18n.t(:"date.abbr_month_names", :locale => locale, :format => format)[object.mon]
when '%B' then I18n.t(:"date.month_names", :locale => locale, :format => format)[object.mon] when '%p' then I18n.t(:"time.#{object.hour < 12 ? :am : :pm}", :locale => locale, :format => format) if object.respond_to? :hour end
MissingTranslationData # no translation was found for the requested key InvalidLocale # the locale set to I18n.locale is invalid (e.g. nil)
I18n.backend = Globalize::Backend::Static.new
module I18n def just_raise_that_exception(*args) raise args.first end end I18n.exception_handler = :just_raise_that_exception
The ruby on rails i18n core api-Neeraj Kumar
The ruby on rails i18n core api-Neeraj Kumar
The ruby on rails i18n core api-Neeraj Kumar

The ruby on rails i18n core api-Neeraj Kumar

  • 9.
    before_filter :set_locale def set_locale # if params[:locale] is nil then I18n.default_locale will be used I18n.locale = params[:locale] end
  • 11.
    # app/controllers/application_controller.rb def default_url_options(options= {}) logger.debug “default_url_options is passed options: #{options.inspect}n” {:locale => I18n.locale} end
  • 12.
    # config/routes.rb map.resources :books,:path_prefix => '/:locale' # => www.example.com/nl/books map.root '/:locale', :controller => “dashboard”
  • 15.
    before_filter :set_locale def set_locale I18n.locale = extract_locale_from_uri end
  • 16.
    def extract_locale_from_tld parsed_locale = request.host.split('.').last I18n.available_locales.include? (parsed_locale.to_sym) ? parsed_locale : nil end
  • 18.
    def set_locale logger.debug = “* Accept-Language: #{request.env['HTTP_ACCEPT_LANGUAGE']}” I18n.locale = extract_locale_from_accept_language_header end
  • 19.
    def extract_locale_from_accept_language_header request.env['HTTP_ACCEPT_LANGUAGE'].scan(/^[a-z] {2}/).first end
  • 20.
    en: activerecord: models: user: foo admin: bar attributes: user: login: “Handle” # => will translate User attribute “login” as “Handle”
  • 21.
    en: activerecord: errors: messages: blank: “can not has nottin” # => u = User.new # => #<User id:nil, etc> # => u.valid? # => false # => u.errors.on(:name) # => “can not has nottin”
  • 23.
    en: activerecord: errors: messages: already_registered: “u already is {{model}}” # => u.errors.on(:email) # => “u already is foo”
  • 24.
    en: activerecord: errors: template: header: one: “1 error prohibted this {{model}} from being saved” other: “{{count}} errors prohibted this {{model}} from being saved” body: “There were problems with the following fields:”
  • 25.
    i18n i18n i18n backend backend core_ext helpers locales exceptions gettext gettext helpers tag fallbacks locale version
  • 26.
    backend Interpolation fast simple active_record active_record compiler Interpolation gettext base compiler missing Interpolation helpers cache compiler store_procs Interpolation Interpolation cascader compiler compiler Interpolation links translation chain compiler Interpolation metadata cldr compiler Interpolation pluralization fallbacks compiler
  • 27.
    def default_locale(locale) @@default_locale = locale.to_sym rescue nil end
  • 28.
    def backend @@backend ||= Backend::Simple.new end
  • 29.
    module I18n module Backend class Simple include Base end end end
  • 30.
    def available_locales @@available_locales ||= backend.available_locales end
  • 33.
    def default_exception_handler(exception, locale,key, options) return exception.message if MissingTranslationData === exception raise exception end
  • 35.
    def config Thread.current[:i18n_config] ||= I18n::Config.new end
  • 37.
    I18n.t :invalid, :scope=> [:active_record, :error_messages] # => I18n.translation :invalid :active_record.error_messa ges.invalid
  • 38.
    I18n.t :foo, :bar=> 'baz' #=> 'foo baz' I18n.t :foo, :count => 1 #=> 'foo' I18n.t :foo, :count => 0 #=> 'foos' I18n.t :foo, :count => 2 #=> 'foos' I18n.t :foo, :default => 'bar'
  • 39.
    def translate(&args) options = args.pop if args.last.is_a?(Hash) key = args.shift locale = options && options.delete(:locale) || config.locale raises = options && options.delete(:raise) config.backend.translate(locale, key, options || {}) rescue I18n::ArgumentError => exception raise exception if raises handle_exception(exception, locale, key, options) end alias :t :translate
  • 40.
    def localize(object, options= {}) locale = options.delete(:locale) || config.locale format = options.delete(:format) || :default config.backend.localize(locale, object, format, options) end alias :l :localize
  • 41.
    def load_translations(*filenames) filenames.each { |filename| load_file(filename) } end
  • 42.
    def load_file(filename) type = File.extname(filename).tr('.', '').downcase raise UnknownFileType.new(type, filename) unless respond_to?(:”load_#(type)”) data = send(:”load_#(type)”, filename) data.each { |locale, d| merge_translation(locale, d) } end
  • 43.
    def store_translations(locale, data,options = {}) merge_translations(locale, data, options) end
  • 44.
    def merge_translations(locale, data,options = {}) locale = locale.to_sym translations[locale] ||= {} separator = options[:separator] || I18n.default_separator data = unwind_keys(data, separator) data = deep_symbolized_keys(data) merger = proc do |key, v1, v2| Hash === v1 && Hash === v2 ? v1.merge(v2, &merger) : (v2 || v1) end translations[locale].merge!(data, &merger) end
  • 45.
    def translate(locale, key,options = {}) raise InvalidLocale.new(locale) unless locale return key.map { |k| translate(locale, k, options) } if key.is_a?(Array) if options.empty? entry = resolve(locale, key, lookup(locale, key), options) raise(I18n::MissingTranslationData.new(locale, key, options)) if entry.nil?
  • 46.
    else count, scope, default = options.values_at(:count, :scope, :default) values = options.reject { |name, value| RESERVED_KEYS.include?(name) } entry = lookup(locale, key, scope, options) entry = entry.nil? && default ? default(locale, key, default, options) : resolve(locale, key, entry, options)
  • 47.
    raise(I18n::MissingTranslationData.new(locale, key, options)) ifentry.nil? entry = pluralize(locale, entry, count) if count entry = interpolate(locale, entry, values) if values end entry end
  • 49.
    case match when '%a' then I18n.t(:"date.abbr_day_names”, :locale => locale, :format => format)[object.wday] when '%A' then I18n.t(:"date.day_names”, :locale => locale, :format => format)[object.wday] when '%b' then I18n.t(:"date.abbr_month_names", :locale => locale, :format => format)[object.mon]
  • 50.
    when '%B' thenI18n.t(:"date.month_names", :locale => locale, :format => format)[object.mon] when '%p' then I18n.t(:"time.#{object.hour < 12 ? :am : :pm}", :locale => locale, :format => format) if object.respond_to? :hour end
  • 52.
    MissingTranslationData # notranslation was found for the requested key InvalidLocale # the locale set to I18n.locale is invalid (e.g. nil)
  • 54.
  • 55.
    module I18n def just_raise_that_exception(*args) raise args.first end end I18n.exception_handler = :just_raise_that_exception