Class Index [+]

Quicksearch

I18n

This module allows you to easily cache all responses from the backend - thus speeding up the I18n aspects of your application quite a bit.

To enable caching you can simply include the Cache module to the Simple backend - or whatever other backend you are using:

  I18n::Backend::Simple.include(I18n::Backend::Cache)

You will also need to set a cache store implementation that you want to use:

  I18n.cache_store = ActiveSupport::Cache.lookup_store(:memory_store)

You can use any cache implementation you want that provides the same API as ActiveSupport::Cache (only the methods # and # are being used).

The cache_key implementation assumes that you only pass values to I18n.translate that return a valid key from # (see www.ruby-doc.org/core/classes/Object.html#M000337).

If you use a lambda as a default value in your translation like this:

  I18n.t(:"date.order", :default => lambda {[:month, :day, :year]})

Then you will always have a cache miss, because each time this method is called the lambda will have a different hash value. If you know the result of the lambda is a constant as in the example above, then to cache this you can make the lambda a constant, like this:

  DEFAULT_DATE_ORDER = lambda {[:month, :day, :year]}
  ...
  I18n.t(:"date.order", :default => DEFAULT_DATE_ORDER)

If the lambda may result in different values for each call then consider also using the Memoize backend.


The Cascade module adds the ability to do cascading lookups to backends that are compatible to the Simple backend.

By cascading lookups we mean that for any key that can not be found the Cascade module strips one segment off the scope part of the key and then tries to look up the key in that scope.

E.g. when a lookup for the key :“foo.bar.baz“ does not yield a result then the segment :bar will be stripped off the scope part :“foo.bar“ and the new scope :foo will be used to look up the key :baz. If that does not succeed then the remaining scope segment :foo will be omitted, too, and again the key :baz will be looked up (now with no scope).

To enable a cascading lookup one passes the :cascade option:

  I18n.t(:'foo.bar.baz', :cascade => true)

This will return the first translation found for :“foo.bar.baz“, :“foo.baz“ or :baz in this order.

The cascading lookup takes precedence over resolving any given defaults. I.e. defaults will kick in after the cascading lookups haven’t succeeded.

This behavior is useful for libraries like ActiveRecord validations where the library wants to give users a bunch of more or less fine-grained options of scopes for a particular key.

Thanks to Clemens Kofler for the initial idea and implementation! See github.com/clemens/i18n-cascading-backend


I18n locale fallbacks are useful when you want your application to use translations from other locales when translations for the current locale are missing. E.g. you might want to use :en translations when translations in your applications main locale :de are missing.

To enable locale fallbacks you can simply include the Fallbacks module to the Simple backend - or whatever other backend you are using:

  I18n::Backend::Simple.include(I18n::Backend::Fallbacks)

Experimental support for using Gettext po files to store translations.

To use this you can simply include the module to the Simple backend - or whatever other backend you are using.

  I18n::Backend::Simple.include(I18n::Backend::Gettext)

Now you should be able to include your Gettext translation (*.po) files to the I18n.load_path so they’re loaded to the backend and you can use them as usual:

 I18n.load_path += Dir["path/to/locales/*.po"]

Following the Gettext convention this implementation expects that your translation files are named by their locales. E.g. the file en.po would contain the translations for the English locale.


The InterpolationCompiler module contains optimizations that can tremendously speed up the interpolation process on the Simple backend.

It works by defining a pre-compiled method on stored translation Strings that already bring all the knowledge about contained interpolation variables etc. so that the actual recurring interpolation will be very fast.

To enable pre-compiled interpolations you can simply include the InterpolationCompiler module to the Simple backend:

  I18n::Backend::Simple.include(I18n::Backend::InterpolationCompiler)

Note that InterpolationCompiler does not yield meaningful results and consequently should not be used with Ruby 1.9 (YARV) but improves performance everywhere else (jRuby, Rubinius and 1.8.7).


Memoize module simply memoizes the values returned by lookup using a flat hash and can tremendously speed up the lookup process in a backend.

To enable it you can simply include the Memoize module to your backend:

  I18n::Backend::Simple.include(I18n::Backend::Memoize)

Notice that it’s the responsibility of the backend to define whenever the cache should be cleaned.


I18n translation metadata is useful when you want to access information about how a translation was looked up, pluralized or interpolated in your application.

  msg = I18n.t(:message, :default => 'Hi!', :scope => :foo)
  msg.translation_metadata
  # => { :key => :message, :scope => :foo, :default => 'Hi!' }

If a :count option was passed to # it will be set to the metadata. Likewise, if any interpolation variables were passed they will also be set.

To enable translation metadata you can simply include the Metadata module into the Simple backend class - or whatever other backend you are using:

  I18n::Backend::Simple.include(I18n::Backend::Metadata)

I18n locale fallbacks are useful when you want your application to use translations from other locales when translations for the current locale are missing. E.g. you might want to use :en translations when translations in your applications main locale :de are missing.

To enable locale specific pluralizations you can simply include the Pluralization module to the Simple backend - or whatever other backend you are using.

  I18n::Backend::Simple.include(I18n::Backend::Pluralization)

You also need to make sure to provide pluralization algorithms to the backend, i.e. include them to your I18n.load_path accordingly.


encoding: utf-8


heavily based on Masao Mutoh’s gettext String interpolation extension github.com/mutoh/gettext/blob/f6566738b981fe0952548c421042ad1e0cdfb31e/lib/gettext/core_ext/string.rb


Locale Fallbacks

Extends the I18n module to hold a fallbacks instance which is set to an instance of I18n::Locale::Fallbacks by default but can be swapped with a different implementation.

Locale fallbacks will compute a number of fallback locales for a given locale. For example:

 I18n.fallbacks[:"es-MX"] # => [:"es-MX",
:es, :en] 

Locale fallbacks always fall back to

  * all parent locales of a given locale (e.g. :es for :"es-MX") first,
  * the current default locales and all of their parents second

The default locales are set to [I18n.default_locale] by default but can be set to something else.

One can additionally add any number of additional fallback locales manually. These will be added before the default locales to the fallback chain. For example:

  # using the default locale as default fallback locale

  I18n.default_locale = :"en-US"
  I18n.fallbacks = I18n::Fallbacks.new(:"de-AT" => :"de-DE")
  I18n.fallbacks[:"de-AT"] # => [:"de-AT", :"de-DE", :de, :"en-US", :en]

  # using a custom locale as default fallback locale

  I18n.fallbacks = I18n::Fallbacks.new(:"en-GB", :"de-AT" => :de, :"de-CH" => :de)
  I18n.fallbacks[:"de-AT"] # => [:"de-AT", :de, :"en-GB", :en]
  I18n.fallbacks[:"de-CH"] # => [:"de-CH", :de, :"en-GB", :en]

  # mapping fallbacks to an existing instance

  # people speaking Catalan also speak Spanish as spoken in Spain
  fallbacks = I18n.fallbacks
  fallbacks.map(:ca => :"es-ES")
  fallbacks[:ca] # => [:ca, :"es-ES", :es, :"en-US", :en]

  # people speaking Arabian as spoken in Palestine also speak Hebrew as spoken in Israel
  fallbacks.map(:"ar-PS" => :"he-IL")
  fallbacks[:"ar-PS"] # => [:"ar-PS", :ar, :"he-IL", :he, :"en-US", :en]
  fallbacks[:"ar-EG"] # => [:"ar-EG", :ar, :"en-US", :en]

  # people speaking Sami as spoken in Finnland also speak Swedish and Finnish as spoken in Finnland
  fallbacks.map(:sms => [:"se-FI", :"fi-FI"])
  fallbacks[:sms] # => [:sms, :"se-FI", :se, :"fi-FI", :fi, :"en-US", :en]

RFC 4646/47 compliant Locale tag implementation that parses locale tags to subtags such as language, script, region, variant etc.

For more information see by en.wikipedia.org/wiki/IETF_language_tag

Rfc4646::Parser does not implement grandfathered tags.


Simple Locale tag implementation that computes subtags by simply splitting the locale tag at ’-’ occurences.


encoding: utf-8


encoding: utf-8


encoding: utf-8


encoding: utf-8


encoding: utf-8


encoding: utf-8


encoding: utf-8


encoding: utf-8


encoding: utf-8


encoding: utf-8


encoding: utf-8

Constants

INTERPOLATION_PATTERN
VERSION
RESERVED_KEYS
RESERVED_KEYS_PATTERN

Public Class Methods

cache_namespace() click to toggle source
    # File lib/i18n/backend/cache.rb, line 49
49:     def cache_namespace
50:       @@cache_namespace
51:     end
cache_namespace=(namespace) click to toggle source
    # File lib/i18n/backend/cache.rb, line 53
53:     def cache_namespace=(namespace)
54:       @@cache_namespace = namespace
55:     end
cache_store() click to toggle source
    # File lib/i18n/backend/cache.rb, line 41
41:     def cache_store
42:       @@cache_store
43:     end
cache_store=(store) click to toggle source
    # File lib/i18n/backend/cache.rb, line 45
45:     def cache_store=(store)
46:       @@cache_store = store
47:     end
config() click to toggle source

Gets I18n configuration object.

    # File lib/i18n.rb, line 17
17:     def config
18:       Thread.current[:i18n_config] ||= I18n::Config.new
19:     end
config=(value) click to toggle source

Sets I18n configuration object.

    # File lib/i18n.rb, line 22
22:     def config=(value)
23:       Thread.current[:i18n_config] = value
24:     end
fallbacks() click to toggle source

Returns the current fallbacks implementation. Defaults to +I18n::Locale::Fallbacks+.

    # File lib/i18n/backend/fallbacks.rb, line 15
15:     def fallbacks
16:       @@fallbacks ||= I18n::Locale::Fallbacks.new
17:     end
fallbacks=(fallbacks) click to toggle source

Sets the current fallbacks implementation. Use this to set a different fallbacks implementation.

    # File lib/i18n/backend/fallbacks.rb, line 20
20:     def fallbacks=(fallbacks)
21:       @@fallbacks = fallbacks
22:     end
interpolate(string, values) click to toggle source
    # File lib/i18n/interpolate/ruby.rb, line 12
12:     def interpolate(string, values)
13:       raise ReservedInterpolationKey.new($1.to_sym, string) if string =~ RESERVED_KEYS_PATTERN
14:       raise ArgumentError.new('Interpolation values must be a Hash.') unless values.kind_of?(Hash)
15:       interpolate_hash(string, values)
16:     end
interpolate_hash(string, values) click to toggle source
    # File lib/i18n/interpolate/ruby.rb, line 18
18:     def interpolate_hash(string, values)
19:       string.gsub(INTERPOLATION_PATTERN) do |match|
20:         if match == '%%'
21:           '%'
22:         else
23:           key = ($1 || $2).to_sym
24:           value = values.key?(key) ? values[key] : raise(MissingInterpolationArgument.new(values, string))
25:           value = value.call(values) if value.respond_to?(:call)
26:           $3 ? sprintf("%#{$3}", value) : value
27:         end
28:       end
29:     end
localize(object, options = {}) click to toggle source

Localizes certain objects, such as dates and numbers to local formatting.

     # File lib/i18n.rb, line 232
232:     def localize(object, options = {})
233:       locale = options.delete(:locale) || config.locale
234:       format = options.delete(:format) || :default
235:       config.backend.localize(locale, object, format, options)
236:     end
normalize_keys(locale, key, scope, separator = nil) click to toggle source

Merges the given locale, key and scope into a single array of keys. Splits keys that contain dots into multiple keys. Makes sure all keys are Symbols.

     # File lib/i18n.rb, line 253
253:     def normalize_keys(locale, key, scope, separator = nil)
254:       separator ||= I18n.default_separator
255: 
256:       keys = []
257:       keys.concat normalize_key(locale, separator)
258:       keys.concat normalize_key(scope, separator)
259:       keys.concat normalize_key(key, separator)
260:       keys
261:     end
perform_caching?() click to toggle source
    # File lib/i18n/backend/cache.rb, line 57
57:     def perform_caching?
58:       !cache_store.nil?
59:     end
reload!() click to toggle source

Tells the backend to reload translations. Used in situations like the Rails development environment. Backends can implement whatever strategy is useful.

    # File lib/i18n.rb, line 43
43:     def reload!
44:       config.backend.reload!
45:     end
translate(*args) click to toggle source

Translates, pluralizes and interpolates a given key using a given locale, scope, and default, as well as interpolation values.

LOOKUP

Translation data is organized as a nested hash using the upper-level keys as namespaces. E.g., ActionView ships with the translation: :date => {:formats => {:short => "%b %d"}}.

Translations can be looked up at any level of this hash using the key argument and the scope option. E.g., in this example I18n.t :date returns the whole translations hash {:formats => {:short => "%b %d"}}.

Key can be either a single key or a dot-separated key (both Strings and Symbols work). E.g., the short format can be looked up using both:

  I18n.t 'date.formats.short'
  I18n.t :'date.formats.short'

Scope can be either a single key, a dot-separated key or an array of keys or dot-separated keys. Keys and scopes can be combined freely. So these examples will all look up the same short date format:

  I18n.t 'date.formats.short'
  I18n.t 'formats.short', :scope => 'date'
  I18n.t 'short', :scope => 'date.formats'
  I18n.t 'short', :scope => %w(date formats)

INTERPOLATION

Translations can contain interpolation variables which will be replaced by values passed to # as part of the options hash, with the keys matching the interpolation variable names.

E.g., with a translation :foo => "foo %{bar}" the option value for the key bar will be interpolated into the translation:

  I18n.t :foo, :bar => 'baz' # => 'foo baz'

PLURALIZATION

Translation data can contain pluralized translations. Pluralized translations are arrays of singluar/plural versions of translations like ['Foo', 'Foos'].

Note that I18n::Backend::Simple only supports an algorithm for English pluralization rules. Other algorithms can be supported by custom backends.

This returns the singular version of a pluralized translation:

  I18n.t :foo, :count => 1 # => 'Foo'

These both return the plural version of a pluralized translation:

  I18n.t :foo, :count => 0 # => 'Foos'
  I18n.t :foo, :count => 2 # => 'Foos'

The :count option can be used both for pluralization and interpolation. E.g., with the translation :foo => ['%{count} foo', '%{count} foos'], count will be interpolated to the pluralized translation:

  I18n.t :foo, :count => 1 # => '1 foo'

DEFAULTS

This returns the translation for :foo or default if no translation was found:

  I18n.t :foo, :default => 'default'

This returns the translation for :foo or the translation for :bar if no translation for :foo was found:

  I18n.t :foo, :default => :bar

Returns the translation for :foo or the translation for :bar or default if no translations for :foo and :bar were found.

  I18n.t :foo, :default => [:bar, 'default']

*BULK LOOKUP*

This returns an array with the translations for :foo and :bar.

  I18n.t [:foo, :bar]

Can be used with dot-separated nested keys:

  I18n.t [:'baz.foo', :'baz.bar']

Which is the same as using a scope option:

  I18n.t [:foo, :bar], :scope => :baz

LAMBDAS

Both translations and defaults can be given as Ruby lambdas. Lambdas will be called and passed the key and options.

E.g. assuming the key :salutation resolves to:

  lambda { |key, options| options[:gender] == 'm' ? "Mr. %{options[:name]}" : "Mrs. %{options[:name]}" }

Then I18n.t(:salutation, :gender => ‘w’, :name => ‘Smith’) will result in “Mrs. Smith”.

It is recommended to use/implement lambdas in an “idempotent” way. E.g. when a cache layer is put in front of I18n.translate it will generate a cache key from the argument values passed to #. Therefor your lambdas should always return the same translations/values per unique combination of argument values.

     # File lib/i18n.rb, line 143
143:     def translate(*args)
144:       options  = args.last.is_a?(Hash) ? args.pop : {}
145:       key      = args.shift
146:       backend  = config.backend
147:       locale   = options.delete(:locale) || config.locale
148:       handling = options.delete(:throw) && :throw || options.delete(:raise) && :raise # TODO deprecate :raise
149: 
150:       raise I18n::ArgumentError if key.is_a?(String) && key.empty?
151: 
152:       result = catch(:exception) do
153:         if key.is_a?(Array)
154:           key.map { |k| backend.translate(locale, k, options) }
155:         else
156:           backend.translate(locale, key, options)
157:         end
158:       end
159:       result.is_a?(MissingTranslation) ? handle_exception(handling, result, locale, key, options) : result
160:     end
translate!(key, options={}) click to toggle source
     # File lib/i18n.rb, line 163
163:     def translate!(key, options={})
164:       translate(key, options.merge(:raise => true))
165:     end
transliterate(*args) click to toggle source

Transliterates UTF-8 characters to ASCII. By default this method will transliterate only Latin strings to an ASCII approximation:

   I18n.transliterate("Ærøskøbing")
   # => "AEroskobing"

   I18n.transliterate("日本語")
   # => "???"

It’s also possible to add support for per-locale transliterations. I18n expects transliteration rules to be stored at i18n.transliterate.rule.

Transliteration rules can either be a Hash or a Proc. Procs must accept a single string argument. Hash rules inherit the default transliteration rules, while Procs do not.

Examples

Setting a Hash in .yml:

   i18n:
     transliterate:
       rule:
         ü: "ue"
         ö: "oe"

Setting a Hash using Ruby:

    store_translations(:de, :i18n => {
      :transliterate => {
        :rule => {
          "ü" => "ue",
          "ö" => "oe"
        }
      }
    )

Setting a Proc:

    translit = lambda {|string| MyTransliterator.transliterate(string) }
    store_translations(:xx, :i18n => {:transliterate => {:rule => translit})

Transliterating strings:

    I18n.locale = :en
    I18n.transliterate("Jürgen") # => "Jurgen"
    I18n.locale = :de
    I18n.transliterate("Jürgen") # => "Juergen"
    I18n.transliterate("Jürgen", :locale => :en) # => "Jurgen"
    I18n.transliterate("Jürgen", :locale => :de) # => "Juergen"
     # File lib/i18n.rb, line 219
219:     def transliterate(*args)
220:       options      = args.pop if args.last.is_a?(Hash)
221:       key          = args.shift
222:       locale       = options && options.delete(:locale) || config.locale
223:       raises       = options && options.delete(:raise)
224:       replacement  = options && options.delete(:replacement)
225:       config.backend.transliterate(locale, key, replacement)
226:     rescue I18n::ArgumentError => exception
227:       raise exception if raises
228:       handle_exception(exception, locale, key, options)
229:     end
with_locale(tmp_locale = nil) click to toggle source

Executes block with given I18n.locale set.

     # File lib/i18n.rb, line 240
240:     def with_locale(tmp_locale = nil)
241:       if tmp_locale
242:         current_locale = self.locale
243:         self.locale    = tmp_locale
244:       end
245:       yield
246:     ensure
247:       self.locale = current_locale if tmp_locale
248:     end

Private Class Methods

default_exception_handler(exception, locale, key, options) click to toggle source

DEPRECATED. Please use the I18n::ExceptionHandler class instead.

     # File lib/i18n.rb, line 325
325:     def default_exception_handler(exception, locale, key, options)
326:       puts "I18n.default_exception_handler is deprecated. Please use the class I18n::ExceptionHandler instead " +
327:            "(an instance of which is set to I18n.exception_handler by default)."
328:       exception.is_a?(MissingTranslation) ? exception.message : raise(exception)
329:     end
handle_exception(handling, exception, locale, key, options) click to toggle source

Any exceptions thrown in translate will be sent to the @@exception_handler which can be a Symbol, a Proc or any other Object unless they’re forced to be raised or thrown (MissingTranslation).

If exception_handler is a Symbol then it will simply be sent to I18n as a method call. A Proc will simply be called. In any other case the method # will be called on the exception_handler object.

Examples:

  I18n.exception_handler = :default_exception_handler             # this is the default
  I18n.default_exception_handler(exception, locale, key, options) # will be called like this

  I18n.exception_handler = lambda { |*args| ... }                 # a lambda
  I18n.exception_handler.call(exception, locale, key, options)    # will be called like this

 I18n.exception_handler = I18nExceptionHandler.new                # an object
 I18n.exception_handler.call(exception, locale, key, options)     # will be called like this
     # File lib/i18n.rb, line 285
285:     def handle_exception(handling, exception, locale, key, options)
286:       case handling
287:       when :raise
288:         raise(exception.respond_to?(:to_exception) ? exception.to_exception : exception)
289:       when :throw
290:         throw :exception, exception
291:       else
292:         case handler = options[:exception_handler] || config.exception_handler
293:         when Symbol
294:           send(handler, exception, locale, key, options)
295:         else
296:           handler.call(exception, locale, key, options)
297:         end
298:       end
299:     end
normalize_key(key, separator) click to toggle source
     # File lib/i18n.rb, line 301
301:     def normalize_key(key, separator)
302:       normalized_key_cache[separator][key] ||=
303:         case key
304:         when Array
305:           key.map { |k| normalize_key(k, separator) }.flatten
306:         else
307:           keys = key.to_s.split(separator)
308:           keys.delete('')
309:           keys.map! { |k| k.to_sym }
310:           keys
311:         end
312:     end
normalize_translation_keys(locale, key, scope, separator = nil) click to toggle source

DEPRECATED. Use I18n.normalize_keys instead.

     # File lib/i18n.rb, line 319
319:     def normalize_translation_keys(locale, key, scope, separator = nil)
320:       puts "I18n.normalize_translation_keys is deprecated. Please use the class I18n.normalize_keys instead."
321:       normalize_keys(locale, key, scope, separator)
322:     end
normalized_key_cache() click to toggle source
     # File lib/i18n.rb, line 314
314:     def normalized_key_cache
315:       @normalized_key_cache ||= Hash.new { |h,k| h[k] = {} }
316:     end

Disabled; run with --debug to generate this.

[Validate]

Generated with the Darkfish Rdoc Generator 1.1.6.