Class: Traverse::XML

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

Instance Method Summary collapse

Constructor Details

#initialize(document) ⇒ XML

Returns a new instance of XML.



51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
# File 'lib/traverse.rb', line 51

def initialize document
  setup_underlying_document document

  if text_node?
    define_singleton_method "text" do
      @document.children.first.content
    end
  end

  singular_children.group_by(&:name).each do |name, children|
    if children.count == 1
      child = children.first
      if text_only_node? child
        define_singleton_method name do
          child.content.strip
        end
      else
        define_singleton_method name do 
          XML.new child
        end
      end
    else
      define_singleton_method name.pluralize do
        children.map do |child|
          if text_only_node? child
            child.content.strip
          else
            XML.new child
          end
        end
      end
    end
  end

  plural_children.each do |pluralized_child|
    define_singleton_method pluralized_child.name do
      pluralized_child.children.reject do |baby|
        baby.class == Nokogiri::XML::Text
      end.map { |child| XML.new child }
    end
  end

end

Dynamic Method Handling

This class handles dynamic methods through the method_missing method

#method_missing(m, *args, &block) ⇒ Object (private)



111
112
113
# File 'lib/traverse.rb', line 111

def method_missing m, *args, &block
  self[m] or super
end

Instance Method Details

#[](attr) ⇒ Object



95
96
97
# File 'lib/traverse.rb', line 95

def [] attr
  @document.get_attribute attr
end

#_attributes_Object



99
100
101
102
103
104
# File 'lib/traverse.rb', line 99

def _attributes_
  name_value_pairs = @document.attributes.map do |name, attribute|
    [name, attribute.value]
  end
  Hash[ name_value_pairs ]
end

#_children_Object



106
107
108
# File 'lib/traverse.rb', line 106

def _children_
  real_children.map { |child| XML.new child }
end