Module: TTY::Config::Generator

Defined in:
lib/tty/config/generator.rb

Class Method Summary collapse

Class Method Details

.generate(data, separator: '=') ⇒ String

Generate file content based on the data hash

Parameters:

  • data (Hash)

Returns:

  • (String)

    the file content


14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
# File 'lib/tty/config/generator.rb', line 14

def self.generate(data, separator: '=')
  content  = []
  values   = {}
  sections = {}

  data.keys.sort.each do |key|
    val = data[key]
    if val.is_a?(NilClass)
      next
    elsif val.is_a?(Hash) ||
          (val.is_a?(Array) && val.first.is_a?(Hash))
      sections[key] = val
    elsif val.is_a?(Array)
      values[key] = val.join(',')
    else
      values[key] = val
    end
  end

  # values
  values.each do |key, val|
    content << "#{key} #{separator} #{val}"
  end
  content << '' unless values.empty?

  # sections
  sections.each do |section, object|
    next if object.empty? # only add section if values present

    content << "[#{section}]"
    if object.is_a?(Array)
      object = object.reduce({}, :merge!)
    end
    object.each do |key, val|
      val = val.join(',') if val.is_a?(Array)
      content << "#{key} #{separator} #{val}" if val
    end
    content << ''
  end
  content.join("\n")
end