Class: Dry::Schema::Messages::I18n

Inherits:
Abstract
  • Object
show all
Defined in:
lib/dry/schema/messages/i18n.rb

Overview

I18n message backend

Instance Attribute Summary collapse

Instance Method Summary collapse

Methods inherited from Abstract

build, cache, #cache, #call, #hash, #lookup, #lookup_paths, #namespaced, #root, #rule, #rule_lookup_paths, #translate

Constructor Details

#initializeI18n

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.

Returns a new instance of I18n.



15
16
17
18
# File 'lib/dry/schema/messages/i18n.rb', line 15

def initialize
  super
  @t = I18n.method(:t)
end

Instance Attribute Details

#tObject (readonly)



12
13
14
# File 'lib/dry/schema/messages/i18n.rb', line 12

def t
  @t
end

Instance Method Details

#default_localeObject

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.



54
55
56
# File 'lib/dry/schema/messages/i18n.rb', line 54

def default_locale
  I18n.locale || I18n.default_locale || super
end

#get(key, options = EMPTY_HASH) ⇒ String

Get a message for the given key and its options

Parameters:

  • key (Symbol)
  • options (Hash) (defaults to: EMPTY_HASH)

Returns:

  • (String)


28
29
30
# File 'lib/dry/schema/messages/i18n.rb', line 28

def get(key, options = EMPTY_HASH)
  t.(key, options) if key
end

#key?(key, options) ⇒ Boolean

Check if given key is defined

Returns:

  • (Boolean)


37
38
39
40
# File 'lib/dry/schema/messages/i18n.rb', line 37

def key?(key, options)
  I18n.exists?(key, options.fetch(:locale, default_locale)) ||
    I18n.exists?(key, I18n.default_locale)
end

#merge(paths) ⇒ Messages::I18n

Merge messages from an additional path

Parameters:

  • paths (String, Array<String>)

Returns:



49
50
51
# File 'lib/dry/schema/messages/i18n.rb', line 49

def merge(paths)
  prepare(paths)
end

#prepare(paths = config.load_paths) ⇒ Object

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.



59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
# File 'lib/dry/schema/messages/i18n.rb', line 59

def prepare(paths = config.load_paths)
  paths.each do |path|
    data = YAML.load_file(path)

    if custom_top_namespace?(path)
      top_namespace = config.top_namespace

      mapped_data = data
        .map { |k, v| [k, { top_namespace => v[DEFAULT_MESSAGES_ROOT] }] }
        .to_h

      store_translations(mapped_data)
    else
      store_translations(data)
    end
  end

  self
end