Class: Xmlhash::XMLHash

Inherits:
Hash
  • Object
show all
Defined in:
lib/xmlhash.rb,
ext/xmlhash/xmlhash.c

Instance Method Summary collapse

Constructor Details

#initialize(opts = nil) ⇒ XMLHash

Initialize with a hash



57
58
59
# File 'lib/xmlhash.rb', line 57

def initialize(opts = nil)
  self.replace(opts) if opts
end

Instance Method Details

#elements(name) ⇒ Object

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.



16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
# 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) ⇒ Object

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



41
42
43
44
45
# File 'lib/xmlhash.rb', line 41

def get(name)
  sub = self[name]
  return sub if sub
  return XMLHash.new
end

#inspectObject



61
62
63
# File 'lib/xmlhash.rb', line 61

def inspect
  "X(#{super})"
end

#value(name) ⇒ Object

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



49
50
51
52
53
54
# 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