Class: Hydrochlorb::Builder

Inherits:
Object
  • Object
show all
Defined in:
lib/hydrochlorb/builder.rb

Instance Method Summary collapse

Constructor Details

#initialize(options = {}, &block) ⇒ Builder

Returns a new instance of Builder.



4
5
6
7
8
9
10
# File 'lib/hydrochlorb/builder.rb', line 4

def initialize(options = {}, &block)
  @attributes = {}
  @current = @attributes
  @context = nil

  build(&block) if block_given?
end

Dynamic Method Handling

This class handles dynamic methods through the method_missing method

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



22
23
24
25
26
27
28
# File 'lib/hydrochlorb/builder.rb', line 22

def method_missing(method, *args, &block)
  if @context and @context.respond_to?(method)
    @context.send(method, *args, &block)
  else
    add(method, *args, &block)
  end
end

Instance Method Details

#add(*args, &block) ⇒ Object



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
55
# File 'lib/hydrochlorb/builder.rb', line 30

def add(*args, &block)
  if block_given?
    obj = {}
    k = args.first.to_sym

    @current[k] = [] unless @current[k].is_a? Array
    @current[k] << obj

    c = obj
    args[1..-1].each do |k|
      obj = {}
      c[k.to_sym] = obj
      c = obj
    end

    previous = @current
    @current = obj
    instance_eval(&block)
    @current = previous
  elsif args.length > 1
    method = args.shift.to_sym
    @current[method] = args.length == 1 ? args.first : args
  else
    raise ArgumentError, "One key and at least one of values are required: #{args.join(',')}"
  end
end

#build(&block) ⇒ Object



12
13
14
15
16
17
18
19
20
# File 'lib/hydrochlorb/builder.rb', line 12

def build(&block)
  return unless block_given?

  @context = eval('self', block.binding)

  instance_eval(&block)

  self
end

#to_hcl(*args) ⇒ Object



61
62
63
# File 'lib/hydrochlorb/builder.rb', line 61

def to_hcl(*args)
  Hydrochlorb::Serializer.serialize(@attributes, *args)
end

#to_jsonObject



57
58
59
# File 'lib/hydrochlorb/builder.rb', line 57

def to_json
  @attributes.to_json
end