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

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

  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



19
20
21
# File 'lib/hydrochlorb/builder.rb', line 19

def method_missing(method, *args, &block)
  add(method, *args, &block)
end

Instance Method Details

#add(*args, &block) ⇒ Object



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

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



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

def build(&block)
  return unless block_given?

  instance_eval(&block)

  self
end

#to_hcl(*args) ⇒ Object



54
55
56
# File 'lib/hydrochlorb/builder.rb', line 54

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

#to_jsonObject



50
51
52
# File 'lib/hydrochlorb/builder.rb', line 50

def to_json
  @attributes.to_json
end