Class: R18n::Backend

Inherits:
Object
  • Object
show all
Includes:
I18n::Backend::Transliterator
Defined in:
lib/r18n-rails-api/backend.rb

Overview

R18n backend for Rails I18n. You must set R18n I18n object before use this backend:

R18n.set locales, R18n::Loader::Rails

I18n.l Time.now, :format => :full #=> "6th of December, 2009 22:44"

Constant Summary collapse

RESERVED_KEYS =
[:scope, :default, :separator]

Instance Method Summary collapse

Instance Method Details

#available_localesObject

Return array of available locales codes.



85
86
87
# File 'lib/r18n-rails-api/backend.rb', line 85

def available_locales
  R18n.get.available_locales.map { |i| i.code.to_sym }
end

#localize(locale, object, format = :default, options = {}) ⇒ Object

Convert object to String, according to the rules of the current R18n locale. It didn’t use locale argument, only current R18n I18n object. It support Fixnum, Bignum, Float, Time, Date and DateTime.

Support Rails I18n (:default, :short, :long, :long_ordinal, :only_day and :only_second) and R18n (:full, :human, :standard and :month) time formatters.



74
75
76
77
78
79
80
81
82
# File 'lib/r18n-rails-api/backend.rb', line 74

def localize(locale, object, format = :default, options = {})
  i18n = get_i18n(locale)
  if format.is_a? Symbol
    key  = format
    type = object.respond_to?(:sec) ? 'time' : 'date'
    format = i18n[type].formats[key] | format
  end
  i18n.localize(object, format)
end

#reload!Object

Reload R18n I18n object.



90
91
92
# File 'lib/r18n-rails-api/backend.rb', line 90

def reload!
  R18n.get.reload!
end

#translate(locale, key, options = {}) ⇒ Object

Find translation in R18n. It didn’t use locale argument, only current R18n I18n object. Also it doesn’t support Proc and variables in default String option.



38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
# File 'lib/r18n-rails-api/backend.rb', line 38

def translate(locale, key, options = {})
  return key.map { |k| translate(locale, k, options) } if key.is_a?(Array)

  scope, default, separator = options.values_at(*RESERVED_KEYS)
  params = options.reject { |name, value| RESERVED_KEYS.include?(name) }

  result = lookup(locale, scope, key, separator, params)

  if result.is_a? Untranslated
    options = options.reject { |key, value| key == :default }

    default = []        if default.nil?
    default = [default] unless default.is_a? Array

    default.each do |entry|
      if entry.is_a? Symbol
        value = lookup(locale, scope, entry, separator, params)
        return value unless value.is_a? Untranslated
      else
        return entry
      end
    end

    raise ::I18n::MissingTranslationData.new(locale, key, options)
  else
    result
  end
end