Class: Demolisher::Node

Inherits:
Object
  • Object
show all
Defined in:
lib/demolisher.rb

Instance Method Summary collapse

Constructor Details

#initialize(xml, is_root = true) ⇒ Node

Creates a new Node object. If the node is not the root node then the second argument needs to be false.



15
16
17
18
# File 'lib/demolisher.rb', line 15

def initialize(xml, is_root = true)
  @nodes = [xml]
  @nodes.unshift(nil) unless is_root
end

Dynamic Method Handling

This class handles dynamic methods through the method_missing method

#method_missing(meth, *args, &block) ⇒ Object

:nodoc:



36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
# File 'lib/demolisher.rb', line 36

def method_missing(meth, *args, &block) # :nodoc:
  xpath = @nodes.last.find(element_from_symbol(meth))
  return nil if xpath.empty?

  if block_given?
    xpath.each_with_index do |node, idx|
      @nodes.push(node)
      case block.arity
      when 1
        yield idx
      else
        yield
      end
      @nodes.pop
    end
  else
    node = xpath.first

    if node.find('text()').length == 1
      content = node.find('text()').first.content
      case meth.to_s
      when /\?$/
        !! Regexp.new(/(t(rue)?|y(es)?|1)/i).match(content)
      else
        content
      end
    else
      self.class.new(node, false)
    end
  end
end

Instance Method Details

#[](attr_name) ⇒ Object

Access an attribute of the current node Example:

<addressbook>
  <person rel="friend">
    <firstname>Steve</firstname>
  </person>
</addressbook>

xml.addressbook do
  xml.person do
    puts "#{xml.firstname} is a #{xml['rel']}"  #=> "Steve is a friend"
  end
end


33
34
35
# File 'lib/demolisher.rb', line 33

def [](attr_name)
  @nodes.last.attributes[attr_name]
end

#element_from_symbol(sym) ⇒ Object

:nodoc:



70
71
72
# File 'lib/demolisher.rb', line 70

def element_from_symbol(sym) # :nodoc:
  "#{is_root_node? ? '/' : nil}#{sym.to_s.gsub(/[^a-z0-9_]/i, '')}"
end

#is_root_node?Boolean

Indicates if the current node is the root of the XML document

Returns:

  • (Boolean)


74
75
76
# File 'lib/demolisher.rb', line 74

def is_root_node?
  @nodes.size == 1
end

#to_sObject

:nodoc:



67
68
69
# File 'lib/demolisher.rb', line 67

def to_s # :nodoc:
  @nodes.last.content.strip
end