Class: CommonThread::XML::XmlMagic

Inherits:
BlankSlate show all
Defined in:
lib/common_thread/xml/xml_magic.rb

Overview

Class that makes accessing xml objects more like any other ruby object thanks to the magic of method missing

Instance Method Summary collapse

Constructor Details

#initialize(xml, namespace = "") ⇒ XmlMagic

Returns a new instance of XmlMagic.



13
14
15
16
17
18
19
20
21
# File 'lib/common_thread/xml/xml_magic.rb', line 13

def initialize(xml, namespace="")
  if xml.class == REXML::Element or xml.class == Array
    @element = xml
  else
    @xml = REXML::Document.new(xml)
    @element = @xml.root
  end
  @namespace = namespace
end

Dynamic Method Handling

This class handles dynamic methods through the method_missing method

#method_missing(method, selection = nil) ⇒ Object



27
28
29
# File 'lib/common_thread/xml/xml_magic.rb', line 27

def method_missing(method, selection=nil)
  evaluate(method.to_s, selection)
end

Instance Method Details

#[](index, count = nil) ⇒ Object



47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
# File 'lib/common_thread/xml/xml_magic.rb', line 47

def [](index, count = nil)
  if index.is_a?(Fixnum) or index.is_a?(Bignum) or index.is_a?(Integer) or index.is_a?(Range) 
    if @element.is_a?(Array)
      if count
        CommonThread::XML::XmlMagic.new(@element[index, count], @namespace)
      else
        CommonThread::XML::XmlMagic.new(@element[index], @namespace)
      end
    else
      nil
    end
  elsif index.is_a?(Symbol)
    if @element.is_a?(Array)
      if @element.empty?
        nil
      else
        @element[0].attributes[index.to_s]
      end
    else
      @element.attributes[index.to_s]
    end
  end
end

#eachObject



23
24
25
# File 'lib/common_thread/xml/xml_magic.rb', line 23

def each
  @element.each {|e| yield CommonThread::XML::XmlMagic.new(e, @namespace)}
end

#namespace=(namespace) ⇒ Object



31
32
33
34
35
36
37
# File 'lib/common_thread/xml/xml_magic.rb', line 31

def namespace=(namespace)
  if namespace and namespace.length > 0
    @namespace = namespace + ":"
  else
    @namespace = ""
  end
end

#to_sObject



39
40
41
42
43
44
45
# File 'lib/common_thread/xml/xml_magic.rb', line 39

def to_s
  if @element.class == Array
    @element.collect{|e| e.text}.join
  else
    @element.text
  end
end