Class: Saxerator::Builder::HashBuilder

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

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(config, name, attributes) ⇒ HashBuilder

Returns a new instance of HashBuilder.



6
7
8
9
10
11
# File 'lib/saxerator/builder/hash_builder.rb', line 6

def initialize(config, name, attributes)
  @config = config
  @name = config.generate_key_for(name)
  @attributes = normalize_attributes(attributes)
  @children = []
end

Instance Attribute Details

#nameObject (readonly)

Returns the value of attribute name.



4
5
6
# File 'lib/saxerator/builder/hash_builder.rb', line 4

def name
  @name
end

Instance Method Details

#add_node(node) ⇒ Object



13
14
15
# File 'lib/saxerator/builder/hash_builder.rb', line 13

def add_node(node)
  @children << node
end

#add_to_hash_element(hash, name, element) ⇒ Object



53
54
55
56
57
58
59
60
61
62
63
# File 'lib/saxerator/builder/hash_builder.rb', line 53

def add_to_hash_element(hash, name, element)
  name = generate_key(name)
  if hash.key? name
    unless hash[name].is_a?(ArrayElement)
      hash[name] = ArrayElement.new([hash[name]], name)
    end
    hash[name] << element
  else
    hash[name] = element
  end
end

#block_variableObject



65
66
67
68
69
70
# File 'lib/saxerator/builder/hash_builder.rb', line 65

def block_variable
  return to_hash unless @children.any? { |c| c.kind_of?(String) }
  return to_s if @children.all? { |c| c.kind_of?(String) }

  to_array
end

#generate_key(name) ⇒ Object



76
77
78
# File 'lib/saxerator/builder/hash_builder.rb', line 76

def generate_key(name)
  @config.generate_key_for(name)
end

#normalize_attributes(attributes) ⇒ Object



72
73
74
# File 'lib/saxerator/builder/hash_builder.rb', line 72

def normalize_attributes(attributes)
  Hash[attributes.map { |key, value| [generate_key(key), value] }]
end

#to_arrayObject



42
43
44
45
46
47
48
49
50
51
# File 'lib/saxerator/builder/hash_builder.rb', line 42

def to_array
  arr = @children.map do |child|
    if child.kind_of?(String)
      StringElement.new(child)
    else
      child.block_variable
    end
  end
  ArrayElement.new(arr, @name, @attributes)
end

#to_hashObject



21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
# File 'lib/saxerator/builder/hash_builder.rb', line 21

def to_hash
  hash = HashElement.new(@name, @attributes)

  @children.each do |child|
    name = child.name
    element = child.block_variable

    add_to_hash_element(hash, name, element)
  end

  if @config.put_attributes_in_hash?
    @attributes.each do |attribute|
      attribute.each_slice(2) do |name, element|
        add_to_hash_element(hash, name, element)
      end
    end
  end

  hash
end

#to_sObject



17
18
19
# File 'lib/saxerator/builder/hash_builder.rb', line 17

def to_s
  StringElement.new(@children.join, @name, @attributes)
end