class R18n::Loader::Rails

Loader for translations in Rails I18n format:

R18n::I18n.new('en', R18n::Loader::Rails.new)

It use Rails I18n backend to load translations. By default, simple backend will be used, by you can change it, if use extended backend (for example, with ActiveRecord storage):

R18n::I18n.new('en',
               R18n::Loader::Rails.new(I18n::Backend::ActiveRecord.new))

Public Class Methods

new(backend = ::I18n::Backend::Simple.new) click to toggle source

Create new loader for some `backend` from Rails I18n. Backend must have `reload!`, `init_translations` and `translations` methods.

# File lib/r18n-rails-api/loader.rb, line 39
def initialize(backend = ::I18n::Backend::Simple.new)
  @backend = backend
  detect_yaml_private_type
end

Public Instance Methods

==(other) click to toggle source

Is another `loader` is also load Rails translations.

# File lib/r18n-rails-api/loader.rb, line 76
def ==(other)
  self.class == other.class
end
available() click to toggle source

`Array` of locales, which has translations in `I18n.load_path`.

# File lib/r18n-rails-api/loader.rb, line 45
def available
  reload!
  @translations.keys.map { |code| R18n.locale(code) }
end
hash() click to toggle source

Return hash for object and `I18n.load_path`.

# File lib/r18n-rails-api/loader.rb, line 71
def hash
  ::I18n.load_path.hash
end
load(locale) click to toggle source

Return `Hash` with translations for `locale`.

# File lib/r18n-rails-api/loader.rb, line 51
def load(locale)
  initialize_types
  reload!
  @translations[locale.code]
end
reload!() click to toggle source

Reload backend if `I18n.load_path` is changed.

# File lib/r18n-rails-api/loader.rb, line 58
def reload!
  return if defined?(@last_path) && @last_path == ::I18n.load_path

  @last_path = ::I18n.load_path.clone
  @backend.reload!
  @backend.send(:init_translations)
  @translations =
    @backend.send(:translations).map do |locale, values|
      [R18n::Locale.sanitize_code(locale), transform(values)]
    end.to_h
end

Protected Instance Methods

transform(value) click to toggle source

Change pluralization and keys to R18n format.

# File lib/r18n-rails-api/loader.rb, line 83
def transform(value)
  if value.is_a? Hash
    if value.empty?
      value
    elsif value.keys.inject(true) { |a, i| a && RailsPlural.rails?(i) }
      Typed.new(
        'pl',
        value.map { |k, v| [RailsPlural.to_r18n(k), transform(v)] }.to_h
      )
    else
      value.map { |k, v| [k.to_s, transform(v)] }.to_h
    end
  elsif defined?(@private_type_class) && value.is_a?(@private_type_class)
    Typed.new(value.type_id, value.value)
  else
    value
  end
end