Class: ChefCore::Text::TextWrapper

Inherits:
Object
  • Object
show all
Defined in:
lib/chef_core/text/text_wrapper.rb

Overview

TextWrapper is a wrapper around R18n that returns all resolved values as Strings, and raise an error when a given i18n key is not found.

This simplifies behaviors when interfacing with other libraries/components that don’t play nicely with TranslatedString or Untranslated out of R18n.

Defined Under Namespace

Classes: InvalidKey, MissingPlural, TextError

Instance Method Summary collapse

Constructor Details

#initialize(translation_tree) ⇒ TextWrapper

Returns a new instance of TextWrapper.



26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
# File 'lib/chef_core/text/text_wrapper.rb', line 26

def initialize(translation_tree)
  @tree = translation_tree
  @tree.translation_keys.each do |k|
    # Integer keys are not translatable - they're quantity indicators in the key that
    # are instead sent as arguments. If we see one here, it means it was not correctly
    # labeled as plural with !!pl in the parent key
    if k.class == Integer
      raise MissingPlural.new(@tree.instance_variable_get(:@path), k)
    end

    k = k.to_sym
    define_singleton_method k do |*args|
      subtree = @tree.send(k, *args)
      if subtree.methods.include?(:translation_keys) && !subtree.translation_keys.empty?
        # If there are no more possible children, just return the translated value
        TextWrapper.new(subtree)
      else
        subtree.to_s
      end
    end
  end
end

Dynamic Method Handling

This class handles dynamic methods through the method_missing method

#method_missing(name, *args) ⇒ Object

Raises:



49
50
51
# File 'lib/chef_core/text/text_wrapper.rb', line 49

def method_missing(name, *args)
  raise InvalidKey.new(@tree.instance_variable_get(:@path), name)
end