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 =
%i[scope default separator].freeze

Instance Method Summary collapse

Instance Method Details

#available_localesObject

Return array of available locales codes.



88
89
90
# File 'lib/r18n-rails-api/backend.rb', line 88

def available_locales
  R18n.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 `Integer`, `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.



77
78
79
80
81
82
83
84
85
# File 'lib/r18n-rails-api/backend.rb', line 77

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.



93
94
95
# File 'lib/r18n-rails-api/backend.rb', line 93

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.



37
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
66
67
68
# File 'lib/r18n-rails-api/backend.rb', line 37

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 { |opts_key, _value| opts_key == :default }

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

    default.each do |entry|
      case entry
      when Symbol
        value = lookup(locale, scope, entry, separator, params)
        return value unless value.is_a? Untranslated
      when Proc
        proc_key = options.delete(:object) || key
        return entry.call(proc_key, options)
      else
        return entry
      end
    end

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