Class: Translations::Translation

Inherits:
Object
  • Object
show all
Defined in:
lib/translations/translation.rb

Defined Under Namespace

Classes: InvalidKeyException

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(translations) ⇒ Translation

Returns a new instance of Translation.



9
10
11
12
# File 'lib/translations/translation.rb', line 9

def initialize translations
  @locale = translations.keys.first
  @translations = translations[@locale]
end

Instance Attribute Details

#localeObject (readonly)

Returns the value of attribute locale.



7
8
9
# File 'lib/translations/translation.rb', line 7

def locale
  @locale
end

Instance Method Details

#[](key) ⇒ Object



34
35
36
37
38
39
40
41
42
# File 'lib/translations/translation.rb', line 34

def [] key
  key.split(".").inject(@translations) do |translation, key|
    if translation.nil?
      raise InvalidKeyException
    else
      translation[key]
    end
  end
end

#[]=(key, value) ⇒ Object



44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
# File 'lib/translations/translation.rb', line 44

def []= key, value
  parts = key.split(".")

  hash = parts.slice(0, parts.length - 1).inject(@translations) do |translation, key|
    if !translation.has_key? key
      translation[key] = { }
    end

    if !translation[key].is_a? Hash
      translation[key] = { }
    end

    translation[key]
  end

  hash[parts.last] = value
end

#has_key?(key) ⇒ Boolean

Returns:

  • (Boolean)


22
23
24
25
26
27
28
29
30
31
32
# File 'lib/translations/translation.rb', line 22

def has_key? key
  translation = key.split(".").inject(@translations) do |translation, key|
    if translation.nil?
      nil
    else
      translation[key]
    end
  end

  translation != nil
end

#keysObject



14
15
16
# File 'lib/translations/translation.rb', line 14

def keys
  keys_of_nested_hash @translations
end

#missing_keys_from_translation(translation) ⇒ Object



18
19
20
# File 'lib/translations/translation.rb', line 18

def missing_keys_from_translation translation
  translation.keys - keys
end

#move(from, to) ⇒ Object



75
76
77
78
79
80
81
# File 'lib/translations/translation.rb', line 75

def move from, to
  self[to] = self[from]

  remove from
rescue InvalidKeyException
  # If the key does not exist, there is nothing to move
end

#remove(key) ⇒ Object



62
63
64
65
66
67
68
69
70
71
72
73
# File 'lib/translations/translation.rb', line 62

def remove key
  parts = key.split(".")
  last_part = parts.pop

  parent = parts.inject(@translations) do |translation, key|
    if translation.is_a?(Hash)
      translation[key]
    end
  end

  parent.delete(last_part) if parent.is_a?(Hash)
end

#to_hashObject



83
84
85
# File 'lib/translations/translation.rb', line 83

def to_hash
  { @locale => @translations }
end