Class: Terraspace::Seeder::Content

Inherits:
Object
  • Object
show all
Extended by:
Memoist
Defined in:
lib/terraspace/seeder/content.rb

Instance Method Summary collapse

Constructor Details

#initialize(parsed) ⇒ Content

Returns a new instance of Content.



5
6
7
# File 'lib/terraspace/seeder/content.rb', line 5

def initialize(parsed)
  @parsed = parsed
end

Instance Method Details

#all_varsObject



73
74
75
# File 'lib/terraspace/seeder/content.rb', line 73

def all_vars
  select_vars(@parsed)
end

#buildObject



9
10
11
12
13
14
15
16
17
18
19
20
21
# File 'lib/terraspace/seeder/content.rb', line 9

def build
  lines = []
  lines << "# Required variables:" unless required_vars.empty?
  required_vars.each do |name, meta|
    lines << build_line(name, meta)
  end
  lines << "" unless required_vars.empty?
  lines << "# Optional variables:" unless optional_vars.empty?
  optional_vars.each do |name, meta|
    lines << build_line(name, meta)
  end
  lines.join("\n") + "\n"
end

#build_line(name, meta) ⇒ Object



23
24
25
26
27
28
# File 'lib/terraspace/seeder/content.rb', line 23

def build_line(name, meta)
  value = var_value(meta)
  name = "# #{name}" if meta["default"] # optional so add as a comment
  name = "%-#{rpad}s" % name # rpad to align = signs
  "#{name} = #{value}"
end

#desc_example(desc) ⇒ Object



58
59
60
61
62
63
# File 'lib/terraspace/seeder/content.rb', line 58

def desc_example(desc)
  return unless desc
  md = desc.match(/([eE]xample|IE): (.*)/)
  return unless md
  md[2]
end

#escape(type, value) ⇒ Object



41
42
43
44
45
46
47
48
49
50
51
# File 'lib/terraspace/seeder/content.rb', line 41

def escape(type, value)
  if type == "map(string)"
    "{...} # #{type}"
  elsif type&.include?('(') # complex type
    "[...] # #{type}"
  elsif %w[null any true false].include?(value)
    value # no quotes
  else
    %Q|"#{value}"| # add quotes
  end
end

#optional_varsObject



69
70
71
# File 'lib/terraspace/seeder/content.rb', line 69

def optional_vars
  select_vars(@parsed) { |meta| !meta["default"].nil? }
end

#required_varsObject



65
66
67
# File 'lib/terraspace/seeder/content.rb', line 65

def required_vars
  select_vars(@parsed) { |meta|  meta["default"].nil? }
end

#rpadObject



53
54
55
# File 'lib/terraspace/seeder/content.rb', line 53

def rpad
  all_vars.keys.map(&:size).max + 2
end

#select_vars(parsed) ⇒ Object



77
78
79
80
81
82
83
# File 'lib/terraspace/seeder/content.rb', line 77

def select_vars(parsed)
  vars = parsed.dig("variable")
  return [] unless vars
  vars.select do |name,meta|
    block_given? ? yield(meta) : true
  end
end

#var_value(meta) ⇒ Object



30
31
32
33
34
35
36
37
38
39
# File 'lib/terraspace/seeder/content.rb', line 30

def var_value(meta)
  type, default = meta["type"], meta["default"]

  if default
    escape(type, default)
  else
    value = desc_example(meta["description"]) || type || "any"
    escape(type, value)
  end
end