Module: Spree::I18nUtils

Defined in:
lib/spree/i18n_utils.rb

Class Method Summary collapse

Class Method Details

.create_hash(data) ⇒ Object

Creates hash of translation data



14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
# File 'lib/spree/i18n_utils.rb', line 14

def create_hash(data)
  words = {}
  return words unless data
  parent = []
  previous_key = 'base'
  data.split("\n").each do |w|
    next if w.strip.blank? || w.strip[0] == '#'
    (key, value) = w.split(':', 2)
    value ||= ''
    # Determine level of current key in comparison to parent array
    shift = (key =~ /\w/) / 2 - parent.size
    key = key.sub(/^\s+/, '')
    # If key is child of previous key, add previous key as parent
    parent << previous_key if shift > 0
    # If key is not related to previous key, remove parent keys
    (shift*-1).times { parent.pop } if shift < 0
    # Track key in case next key is child of this key
    previous_key = key
    words[parent.join(':') + ':' + key] = value
  end
  words
end

.read_file(filename, basename) ⇒ Object

Retrieve comments, translation data in hash form



6
7
8
9
10
# File 'lib/spree/i18n_utils.rb', line 6

def read_file(filename, basename)
  # Add error checking for failed file read?
  (comments, data) = IO.read(filename).split(/#{basename}:\s*\n/)
  return comments, create_hash(data)
end

.write_file(filename, basename, _comments, words, comment_values = true, _fallback_values = {}) ⇒ Object

Writes to file from translation data hash structure



39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
# File 'lib/spree/i18n_utils.rb', line 39

def write_file(filename, basename, _comments, words, comment_values = true, _fallback_values = {})
  File.open(filename, 'w') do |log|
    log.puts(basename + ": \n")
    words.sort.each do |k, v|
      keys = k.split(':')
      # Add indentation for children keys
      (keys.size - 1).times do
        keys[keys.size - 1] = '  ' + keys[keys.size - 1]
      end
      value = v.strip
      value = ('#' + value) if comment_values && !value.blank?
      log.puts "#{keys[keys.size - 1]}: #{value}\n"
    end
  end
end