Class: Hash

Inherits:
Object
  • Object
show all
Defined in:
lib/hcl2-rb/formatter.rb

Instance Method Summary collapse

Instance Method Details

#has_child?Boolean



2
3
4
5
6
7
8
9
10
# File 'lib/hcl2-rb/formatter.rb', line 2

def has_child?
  return false if empty?

  each do |_k, v|
    return false unless v.is_a?(Hash)
  end

  true
end

#to_hcl2(spaces: 2, tab: 0) ⇒ Object



12
13
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
# File 'lib/hcl2-rb/formatter.rb', line 12

def to_hcl2(spaces: 2, tab: 0)
  hcl2 = []

  each do |k, v|
    case v
    when Numeric, String, TrueClass, FalseClass
      hcl2.push("#{k} = #{v.to_hcl2}\n")
    when Array
      if v.has_child?
        v.each do |child|
          hcl2.push({ "#{k}": child }.to_hcl2)
        end
      else
        hcl2.push("#{k} = #{v.to_hcl2}")
      end
    when Hash
      labels = HCL2::Helpers.dfs(v)
      labels.each do |label|
        # It creates a label string and we shouldn't
        # forget about addition space before this one
        n = label.empty? ? nil : label.map { |l| l&.to_hcl2 }.join(' ').prepend(' ') # It creates label string

        # We should go deeper to format child attributes
        c = label.empty? ? v : v.dig(*label)

        hcl2.push("#{k}#{n} {")
        hcl2.push(c.to_hcl2(spaces: spaces, tab: 1))
        hcl2.push("}\n")
      end
    else
      raise "#{v.class.name} can't be formatted to HCL2"
    end
  end

  hcl2.map { |v| v.prepend(' ' * spaces * tab) }.join("\n")
end