module I18n
def cache_namespace
def cache_namespace @@cache_namespace end
def cache_namespace=(namespace)
def cache_namespace=(namespace) @@cache_namespace = namespace end
def cache_store
def cache_store @@cache_store end
def cache_store=(store)
def cache_store=(store) @@cache_store = store end
def config
def config Thread.current[:i18n_config] ||= I18n::Config.new end
def config=(value)
def config=(value) Thread.current[:i18n_config] = value end
def default_exception_handler(exception, locale, key, options)
def default_exception_handler(exception, locale, key, options) puts "I18n.default_exception_handler is deprecated. Please use the class I18n::ExceptionHandler instead " + "(an instance of which is set to I18n.exception_handler by default)." exception.is_a?(MissingTranslation) ? exception.message : raise(exception) end
def fallbacks
def fallbacks @@fallbacks ||= I18n::Locale::Fallbacks.new end
def fallbacks=(fallbacks)
def fallbacks=(fallbacks) @@fallbacks = fallbacks end
def handle_exception(handling, exception, locale, key, options)
I18n.exception_handler = I18nExceptionHandler.new # an object
I18n.exception_handler.call(exception, locale, key, options) # will be called like this
I18n.exception_handler = lambda { |*args| ... } # a lambda
I18n.default_exception_handler(exception, locale, key, options) # will be called like this
I18n.exception_handler = :default_exception_handler # this is the default
Examples:
method #call will be called on the exception_handler object.
a method call. A Proc will simply be called. In any other case the
If exception_handler is a Symbol then it will simply be sent to I18n as
be raised or thrown (MissingTranslation).
which can be a Symbol, a Proc or any other Object unless they're forced to
Any exceptions thrown in translate will be sent to the @@exception_handler
def handle_exception(handling, exception, locale, key, options) case handling when :raise raise(exception.respond_to?(:to_exception) ? exception.to_exception : exception) when :throw throw :exception, exception else case handler = options[:exception_handler] || config.exception_handler when Symbol send(handler, exception, locale, key, options) else handler.call(exception, locale, key, options) end end end
def interpolate(string, values)
Return String or raises MissingInterpolationArgument exception.
def interpolate(string, values) raise ReservedInterpolationKey.new($1.to_sym, string) if string =~ RESERVED_KEYS_PATTERN raise ArgumentError.new('Interpolation values must be a Hash.') unless values.kind_of?(Hash) interpolate_hash(string, values) end
def interpolate_hash(string, values)
def interpolate_hash(string, values) string.gsub(INTERPOLATION_PATTERN) do |match| if match == '%%' '%' else key = ($1 || $2).to_sym value = if values.key?(key) values[key] else config.missing_interpolation_argument_handler.call(key, values, string) end value = value.call(values) if value.respond_to?(:call) $3 ? sprintf("%#{$3}", value) : value end end end
def localize(object, options = nil)
def localize(object, options = nil) options = options ? options.dup : {} locale = options.delete(:locale) || config.locale format = options.delete(:format) || :default config.backend.localize(locale, object, format, options) end
def normalize_key(key, separator)
def normalize_key(key, separator) normalized_key_cache[separator][key] ||= case key when Array key.map { |k| normalize_key(k, separator) }.flatten else keys = key.to_s.split(separator) keys.delete('') keys.map! { |k| k.to_sym } keys end end
def normalize_keys(locale, key, scope, separator = nil)
Splits keys that contain dots into multiple keys. Makes sure all
Merges the given locale, key and scope into a single array of keys.
def normalize_keys(locale, key, scope, separator = nil) separator ||= I18n.default_separator keys = [] keys.concat normalize_key(locale, separator) keys.concat normalize_key(scope, separator) keys.concat normalize_key(key, separator) keys end
def normalize_translation_keys(locale, key, scope, separator = nil)
def normalize_translation_keys(locale, key, scope, separator = nil) puts "I18n.normalize_translation_keys is deprecated. Please use the class I18n.normalize_keys instead." normalize_keys(locale, key, scope, separator) end
def normalized_key_cache
def normalized_key_cache @normalized_key_cache ||= Hash.new { |h,k| h[k] = {} } end
def perform_caching?
def perform_caching? !cache_store.nil? end
def reload!
Rails development environment. Backends can implement whatever strategy
Tells the backend to reload translations. Used in situations like the
def reload! config.backend.reload! end
def translate(*args)
always return the same translations/values per unique combination of argument
from the argument values passed to #translate. Therefor your lambdas should
a cache layer is put in front of I18n.translate it will generate a cache key
It is recommended to use/implement lambdas in an "idempotent" way. E.g. when
Then I18n.t(:salutation, :gender => 'w', :name => 'Smith') will result in "Mrs. Smith".
lambda { |key, options| options[:gender] == 'm' ? "Mr. %{options[:name]}" : "Mrs. %{options[:name]}" }
E.g. assuming the key :salutation resolves to:
called and passed the key and options.
Both translations and defaults can be given as Ruby lambdas. Lambdas will be
*LAMBDAS*
I18n.t [:foo, :bar], :scope => :baz
Which is the same as using a scope option:
I18n.t [:'baz.foo', :'baz.bar']
Can be used with dot-separated nested keys:
I18n.t [:foo, :bar]
This returns an array with the translations for :foo and :bar.
*BULK LOOKUP*
I18n.t :foo, :default => [:bar, 'default']
or default if no translations for :foo and :bar were found.
Returns the translation for :foo or the translation for :bar
I18n.t :foo, :default => :bar
translation for :foo was found:
This returns the translation for :foo or the translation for :bar if no
I18n.t :foo, :default => 'default'
This returns the translation for :foo or default if no translation was found:
*DEFAULTS*
I18n.t :foo, :count => 1 # => '1 foo'
be interpolated to the pluralized translation:
:foo => ['%{count} foo', '%{count} foos'], count will
E.g., with the translation
The :count option can be used both for pluralization and interpolation.
I18n.t :foo, :count => 2 # => 'Foos'
I18n.t :foo, :count => 0 # => 'Foos'
These both return the plural version of a pluralized translation:
I18n.t :foo, :count => 1 # => 'Foo'
This returns the singular version of a pluralized translation:
pluralization rules. Other algorithms can be supported by custom backends.
Note that I18n::Backend::Simple only supports an algorithm for English
are arrays of singluar/plural versions of translations like ['Foo', 'Foos'].
Translation data can contain pluralized translations. Pluralized translations
*PLURALIZATION*
I18n.t :foo, :bar => 'baz' # => 'foo baz'
value for the key +bar+ will be interpolated into the translation:
E.g., with a translation :foo => "foo %{bar}" the option
the interpolation variable names.
values passed to #translate as part of the options hash, with the keys matching
Translations can contain interpolation variables which will be replaced by
*INTERPOLATION*
I18n.t 'short', :scope => %w(date formats)
I18n.t 'short', :scope => 'date.formats'
I18n.t 'formats.short', :scope => 'date'
I18n.t 'date.formats.short'
examples will all look up the same short date format:
or dot-separated keys. Keys and scopes can be combined freely. So these
Scope can be either a single key, a dot-separated key or an array of keys
I18n.t :'date.formats.short'
I18n.t 'date.formats.short'
work). E.g., the short format can be looked up using both:
Key can be either a single key or a dot-separated key (both Strings and Symbols
returns the whole translations hash {:formats => {:short => "%b %d"}}.
and the scope option. E.g., in this example I18n.t :date
Translations can be looked up at any level of this hash using the key argument
:date => {:formats => {:short => "%b %d"}}.
as namespaces. E.g., ActionView ships with the translation:
Translation data is organized as a nested hash using the upper-level keys
*LOOKUP*
scope, and default, as well as interpolation values.
Translates, pluralizes and interpolates a given key using a given locale,
def translate(*args) options = args.last.is_a?(Hash) ? args.pop.dup : {} key = args.shift backend = config.backend locale = options.delete(:locale) || config.locale handling = options.delete(:throw) && :throw || options.delete(:raise) && :raise # TODO deprecate :raise raise I18n::ArgumentError if key.is_a?(String) && key.empty? result = catch(:exception) do if key.is_a?(Array) key.map { |k| backend.translate(locale, k, options) } else backend.translate(locale, key, options) end end result.is_a?(MissingTranslation) ? handle_exception(handling, result, locale, key, options) : result end
def translate!(key, options={})
Wrapper for translate that adds :raise => true. With
def translate!(key, options={}) translate(key, options.merge(:raise => true)) end
def transliterate(*args)
I18n.transliterate("Jürgen", :locale => :en) # => "Jurgen"
I18n.transliterate("Jürgen") # => "Juergen"
I18n.locale = :de
I18n.transliterate("Jürgen") # => "Jurgen"
I18n.locale = :en
Transliterating strings:
store_translations(:xx, :i18n => {:transliterate => {:rule => translit})
translit = lambda {|string| MyTransliterator.transliterate(string) }
Setting a Proc:
)
}
}
"ö" => "oe"
"ü" => "ue",
:rule => {
:transliterate => {
store_translations(:de, :i18n => {
Setting a Hash using Ruby:
ö: "oe"
ü: "ue"
rule:
transliterate:
i18n:
Setting a Hash in
*Examples*
rules, while Procs do not.
single string argument. Hash rules inherit the default transliteration
Transliteration rules can either be a Hash or a Proc. Procs must accept a
i18n.transliterate.rule.
expects transliteration rules to be stored at
It's also possible to add support for per-locale transliterations. I18n
# => "???"
I18n.transliterate("日本語")
# => "AEroskobing"
I18n.transliterate("Ærøskøbing")
transliterate only Latin strings to an ASCII approximation:
Transliterates UTF-8 characters to ASCII. By default this method will
def transliterate(*args) options = args.pop.dup if args.last.is_a?(Hash) key = args.shift locale = options && options.delete(:locale) || config.locale handling = options && (options.delete(:throw) && :throw || options.delete(:raise) && :raise) replacement = options && options.delete(:replacement) config.backend.transliterate(locale, key, replacement) rescue I18n::ArgumentError => exception handle_exception(handling, exception, locale, key, options || {}) end
def with_locale(tmp_locale = nil)
def with_locale(tmp_locale = nil) if tmp_locale current_locale = self.locale self.locale = tmp_locale end yield ensure self.locale = current_locale if tmp_locale end