Class: SlimKeyfy::Slimutils::Merger

Inherits:
Object
  • Object
show all
Defined in:
lib/slimkeyfy/slimutils/hash_merging.rb

Class Method Summary collapse

Class Method Details

.enhance_key_on_collision(translations, translation_key_name) ⇒ Object



23
24
25
26
27
28
29
30
31
# File 'lib/slimkeyfy/slimutils/hash_merging.rb', line 23

def self.enhance_key_on_collision(translations, translation_key_name)
  num = 1
  k = "#{translation_key_name}_#{num}"
  while extract_value(k, translations) != nil do
    k = "#{translation_key_name}_#{num}"
    num += 1
  end
  k
end

.extract_value(dotted_key, translations, default = nil) ⇒ Object



41
42
43
44
45
46
47
48
49
50
51
52
# File 'lib/slimkeyfy/slimutils/hash_merging.rb', line 41

def self.extract_value(dotted_key, translations, default=nil)
  key, value = dotted_key.split(".", 2)
  if key != nil and translations.has_key?(key) then
    if value != nil then
      extract_value(value, translations[key])
    else
      translations[key]
    end
  else
    default
  end
end

.generate_dotted_key(old_dotted_key, new_name) ⇒ Object



33
34
35
# File 'lib/slimkeyfy/slimutils/hash_merging.rb', line 33

def self.generate_dotted_key(old_dotted_key, new_name)
  "#{old_dotted_key.split(".")[0..-2].join(".")}.#{new_name}"
end

.key_to_hash(dotted_key, translation) ⇒ Object



37
38
39
# File 'lib/slimkeyfy/slimutils/hash_merging.rb', line 37

def self.key_to_hash(dotted_key, translation)
  {dotted_key => translation}.explode
end

.merge_hashes(old_translations = {}, new_translations = {}) ⇒ Object



2
3
4
5
6
7
8
# File 'lib/slimkeyfy/slimutils/hash_merging.rb', line 2

def self.merge_hashes(old_translations={}, new_translations={})
  key = new_translations.keys.first
  new_translations[key].keys.each do |top_key|
    new_translations[key][top_key]
  end
  old_translations.merge(new_translations["translation_key"])
end

.merge_single_translation(translations, translation_key, translation) ⇒ Object



10
11
12
13
14
15
16
17
18
19
20
21
# File 'lib/slimkeyfy/slimutils/hash_merging.rb', line 10

def self.merge_single_translation(translations, translation_key, translation)
  k = translation_key
  name = k.split(".").last
  value = extract_value(k, translations)
  if value != nil and value != translation then
    name = enhance_key_on_collision(translations, name)
    k = generate_dotted_key(k, name)
  end
  h = key_to_hash(k, translation)
  translations = translations.deep_merge(h)
  [translations, k, translation]
end