class Xmlhash::XMLHash

Public Class Methods

new(opts = nil) click to toggle source

Initialize with a hash

# File lib/xmlhash.rb, line 57
def initialize(opts = nil)
  self.replace(opts) if opts
end

Public Instance Methods

elements(name) { |sub| ... } click to toggle source

Return an array of elements or []. It requires a plain string as argument

This makes it easy to write code that assumes an array. If there is just a single child in the XML, it will be wrapped in a single-elemnt array and if there are no children, an empty array is returned.

You can also pass a block to iterate over all childrens.

# File lib/xmlhash.rb, line 16
def elements(name)
  unless name.kind_of? String
    raise ArgumentError, "expected string"
  end
  sub = self[name]
  return [] if !sub || sub.empty?
  unless sub.kind_of? Array
    if block_given?
      yield sub
      return
    else
      return [sub]
    end
  end
  return sub unless block_given?
  sub.each do |n|
    yield n
  end
end
get(name) click to toggle source

Return the element by the given name or an empty hash

This makes it easy to write code that assumes a child to be present. obj[“b”] will give you a “[] not defined for nil”. obj.get(“a”) will give you nil

# File lib/xmlhash.rb, line 41
def get(name)
  sub = self[name]
  return sub if sub
  return XMLHash.new
end
inspect() click to toggle source
# File lib/xmlhash.rb, line 61
def inspect
  "X(#{super})"
end
value(name) click to toggle source

Return the value of the name or nil if nothing is there

# File lib/xmlhash.rb, line 49
def value(name)
  sub = self[name.to_s]
  return nil unless sub
  return '' if sub.empty? # avoid {}
  return sub
end