Class: Objectify::Xml

Inherits:
Object
  • Object
show all
Defined in:
lib/objectify_xml.rb,
lib/objectify_xml/dsl.rb

Direct Known Subclasses

DocumentParser, ElementParser

Defined Under Namespace

Modules: Dsl

Constant Summary collapse

VERSION =
'0.2.1'

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(xml, parent = nil) ⇒ Xml

Returns a new instance of Xml.



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

def initialize(xml, parent = nil)
  @parent = parent
  @attributes = {}
  xml = self.class.first_element(xml)
  primary_xml_element(xml) if xml
end

Instance Attribute Details

#attributesObject (readonly)

A hash containing the values of the xml document’s nodes. The data is usually better accessed through the getter and setter methods that are created for all attributes, has_one and has_many associations.



20
21
22
# File 'lib/objectify_xml.rb', line 20

def attributes
  @attributes
end

#parentObject (readonly)

When child nodes are created, they are given the name of the node that created them which is available here.



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

def parent
  @parent
end

Class Method Details

.first_element(xml) ⇒ Object



27
28
29
30
31
32
33
34
35
36
37
38
39
# File 'lib/objectify_xml.rb', line 27

def self.first_element(xml)
  return if xml.nil?
  if xml.is_a?(String) or xml.is_a?(File)
    xml = Nokogiri::XML.parse(xml)
  end
  # skip the <?xml?> tag
  xml = xml.child if xml.class == Nokogiri::XML::Document
  while xml and xml.class != Nokogiri::XML::Element
    # skips past things like xml-stylesheet declarations.
    xml = xml.next
  end
  xml
end

.inherited(target) ⇒ Object



22
23
24
25
# File 'lib/objectify_xml.rb', line 22

def self.inherited(target)
  # The Dsl module is added to every class that inherits from this
  target.extend Dsl
end

Instance Method Details

#inspectObject



48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
# File 'lib/objectify_xml.rb', line 48

def inspect
  begin
    attrs = (attributes || {}).map do |k,v| 
      if v.is_a? Objectify::Xml
        "#{ k }:#{ v.class.name }"
      elsif v.is_a? Array
        "#{ k }:#{ v.length }"
      else
        k.to_s
      end
    end
    "<#{ self.class.name } #{ attrs.join(', ') }>"
  rescue => e
    "<#{ self.class.name } Error inspecting class: #{ e.name } #{ e.message }>"
  end
end

#pretty_print(q) ⇒ Object



65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
# File 'lib/objectify_xml.rb', line 65

def pretty_print(q)
  begin
    q.object_group(self) do
      q.breakable
      q.seplist(attributes, nil, :each_pair) do |k, v|
        q.text "#{ k.to_s }: "
        if v.is_a? String and v.length > 200
          q.text "#{ v[0..80] }...".inspect
        else
          q.pp v
        end
      end
    end
  rescue => e
    q.text "<#{ self.class.name } Error inspecting class: #{ e.name } #{ e.message }>"
  end
end