class Saxerator::Builder::HashBuilder

Attributes

name[R]

Public Class Methods

new(config, name, attributes) click to toggle source
# 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

Public Instance Methods

add_node(node) click to toggle source
# File lib/saxerator/builder/hash_builder.rb, line 13
def add_node(node)
  @children << node
end
add_to_hash_element(hash, name, element) click to toggle source
# 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_variable() click to toggle source
# 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) click to toggle source
# File lib/saxerator/builder/hash_builder.rb, line 76
def generate_key(name)
  @config.generate_key_for(name)
end
normalize_attributes(attributes) click to toggle source
# File lib/saxerator/builder/hash_builder.rb, line 72
def normalize_attributes(attributes)
  Hash[attributes.map { |key, value| [generate_key(key), value] }]
end
to_array() click to toggle source
# 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_hash() click to toggle source
# 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_s() click to toggle source
# File lib/saxerator/builder/hash_builder.rb, line 17
def to_s
  StringElement.new(@children.join, @name, @attributes)
end