Class: TFDSL::Block

Inherits:
Object
  • Object
show all
Defined in:
lib/tfdsl/block.rb

Overview

This class is the representation of terraform configuration block www.terraform.io/docs/configuration/

Direct Known Subclasses

DataSource, Locals, Provider, Resource, TFModule, Terraform, Variable

Constant Summary collapse

@@formatter =
Formatter.new

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(&block) ⇒ Block

Returns a new instance of Block.



7
8
9
10
# File 'lib/tfdsl/block.rb', line 7

def initialize(&block)
  @__blocks__ = []
  instance_eval(&block) if block_given?
end

Dynamic Method Handling

This class handles dynamic methods through the method_missing method

#method_missing(method_name, *args, &block) ⇒ Object



12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
# File 'lib/tfdsl/block.rb', line 12

def method_missing(method_name, *args, &block)
  super if [:respond_to_missing?].include? method_name
  method = method_name.to_s.gsub(/=$/, '')

  if block_given?
    r = Block.new
    r.__type__ = method
    r.__labels__ = args
    @__blocks__ << r
    return r.instance_eval(&block)
  end

  return instance_variable_set "@#{method}", *args unless args.empty?
  return instance_variable_get "@#{method}" if args.empty?
end

Instance Attribute Details

#__labels__Object (readonly)

Returns the value of attribute __labels__.



5
6
7
# File 'lib/tfdsl/block.rb', line 5

def __labels__
  @__labels__
end

#__type__Object (readonly)

Returns the value of attribute __type__.



5
6
7
# File 'lib/tfdsl/block.rb', line 5

def __type__
  @__type__
end

Instance Method Details

#respond_to_missing?(_method_name, _include_private = true) ⇒ Boolean

Returns:

  • (Boolean)


28
29
30
# File 'lib/tfdsl/block.rb', line 28

def respond_to_missing?(_method_name, _include_private = true)
  true
end

#to_json_repr(depth = 0) ⇒ Object



44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
# File 'lib/tfdsl/block.rb', line 44

def to_json_repr(depth = 0)
  block = { 'tmp' => {} }

  ref = block['tmp']

  labels = __labels__.dup
  labels = [__type__] + labels if !__type__.empty? && depth.zero?

  labels.each do |l|
    ref[l] = {} if ref[l].nil?
    ref = ref[l]
  end

  instance_variables.each do |var|
    var_name = var.to_s.gsub(/^@/, '')
    next if var_name =~ /^__/

    ref[var_name] = send var_name
  end

  __blocks__.each do |b|
    json = b.to_json_repr depth + 1
    if b.__labels__.empty?
      ref[b.__type__] = json
    else
      ref[b.__type__] = [] if ref[b.__type__].nil?
      ref[b.__type__] << json
    end
  end

  block['tmp']
end

#to_sObject



40
41
42
# File 'lib/tfdsl/block.rb', line 40

def to_s
  to_tf
end

#to_strObject



36
37
38
# File 'lib/tfdsl/block.rb', line 36

def to_str
  to_tf
end

#to_tfObject



32
33
34
# File 'lib/tfdsl/block.rb', line 32

def to_tf
  @@formatter.format self
end