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
12
# File 'lib/saxerator/builder/hash_builder.rb', line 6

def initialize(config, name, attributes)
  @config = config
  @name = config.generate_key_for(name)
  @attributes = attributes
  @children = []
  @text = false
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



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

def add_node(node)
  @text = true if node.is_a? String
  @children << node
end

#add_to_hash_element(hash, name, element) ⇒ Object



49
50
51
52
53
54
55
56
57
58
59
60
# File 'lib/saxerator/builder/hash_builder.rb', line 49

def add_to_hash_element( hash, name, element)
  name = @config.generate_key_for(name)
  if hash[name]
    if !hash[name].is_a?(Array)
      hash[name] = ArrayElement[hash[name]]
      hash[name].name = name
    end
    hash[name] << element
  else
    hash[name] = element
  end
end

#block_variableObject



62
63
64
65
66
# File 'lib/saxerator/builder/hash_builder.rb', line 62

def block_variable
  return to_s if @text
  return to_hash if @children.count > 0
  to_empty_element
end

#to_empty_elementObject



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

def to_empty_element
  EmptyElement.new(@name, @attributes)
end

#to_hashObject



27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
# File 'lib/saxerator/builder/hash_builder.rb', line 27

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



23
24
25
# File 'lib/saxerator/builder/hash_builder.rb', line 23

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