Class: Translate::KeysKeys

Inherits:
Object
  • Object
show all
Defined in:
lib/translate/keys.rb

Class Method Summary (collapse)

Instance Method Summary (collapse)

Class Method Details

+ (Object) deep_merge!(hash1, hash2)

deep_merge by Stefan Rusterholz, see www.ruby-forum.com/topic/142809



81
82
83
84
# File 'lib/translate/keys.rb', line 81

def self.deep_merge!(hash1, hash2)
  merger = proc { |key, v1, v2| Hash === v1 && Hash === v2 ? v1.merge(v2, &merger) : v2 }
  hash1.merge!(hash2, &merger)
end

+ (Object) files

Allows keys extracted from lookups in files to be cached



6
7
8
# File 'lib/translate/keys.rb', line 6

def self.files
  @@files ||= Translate::Keys.new.files
end

+ (Object) files=(files)

Allows flushing of the files cache



11
12
13
# File 'lib/translate/keys.rb', line 11

def self.files=(files)
  @@files = files
end

+ (Object) to_deep_hash(hash)

Convert something like:

{'pressrelease.label.one' => "Pressmeddelande"}

to:

{

:pressrelease => {
  :label => {
    :one => "Pressmeddelande"
  }
 }

}



70
71
72
73
74
75
76
77
78
# File 'lib/translate/keys.rb', line 70

def self.to_deep_hash(hash)
  hash.inject({}) do |deep_hash, (key, value)|
    keys = key.to_s.split('.').reverse
    leaf_key = keys.shift
    key_hash = keys.inject({leaf_key.to_sym => value}) { |hash, key| {key.to_sym => hash} }
    deep_merge!(deep_hash, key_hash)
    deep_hash
  end
end

+ (Object) to_shallow_hash(hash)

Convert something like:

{

:pressrelease => {
  :label => {
    :one => "Pressmeddelande"
  }
 }

}

to:

{'pressrelease.label.one' => "Pressmeddelande"}


44
45
46
47
48
49
50
51
52
53
54
55
# File 'lib/translate/keys.rb', line 44

def self.to_shallow_hash(hash)
  hash.inject({}) do |shallow_hash, (key, value)|
    if value.is_a?(Hash)
      to_shallow_hash(value).each do |sub_key, sub_value|
        shallow_hash[[key, sub_key].join(".")] = sub_value
      end
    else
      shallow_hash[key.to_s] = value
    end
    shallow_hash
  end
end

Instance Method Details

- (Object) files Also known as: to_hash



15
16
17
# File 'lib/translate/keys.rb', line 15

def files
  @files ||= extract_files
end

- (Object) i18n_keys(locale)



25
26
27
28
# File 'lib/translate/keys.rb', line 25

def i18n_keys(locale)
  I18n.backend.send(:init_translations) unless I18n.backend.initialized?
  extract_i18n_keys(I18n.backend.send(:translations)[locale.to_sym]).sort
end

- (Object) keys Also known as: to_a



20
21
22
# File 'lib/translate/keys.rb', line 20

def keys
  files.keys
end