Class: OBIX::Objects::Base

Inherits:
Object
  • Object
show all
Extended by:
Tag
Defined in:
lib/obix/objects/base.rb

Direct Known Subclasses

Object

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Methods included from Tag

attribute, tag

Constructor Details

#initialize(&block) ⇒ Base

Returns a new instance of Base.



9
10
11
12
13
14
15
16
17
18
# File 'lib/obix/objects/base.rb', line 9

def initialize &block
  @attributes = {}
  @objects    = []

  if block_given?
    builder = OBIX::Builder.new self, &block

    @objects = builder.objects
  end
end

Instance Attribute Details

#objectsObject

Returns the value of attribute objects.



7
8
9
# File 'lib/obix/objects/base.rb', line 7

def objects
  @objects
end

#parentObject

Returns the value of attribute parent.



7
8
9
# File 'lib/obix/objects/base.rb', line 7

def parent
  @parent
end

Class Method Details

.parse(element, parent = nil) ⇒ Object

Parse an XML element as OBIX.

element - A Nokogiri::XML::Node describing an element. parent - An Objects::Object instance or derivative thereof describing

the object's parent.

Returns an Object instance or derivative thereof.



57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
# File 'lib/obix/objects/base.rb', line 57

def parse element, parent = nil
  klass = Objects.find element.name

  object = klass.new

  element.attributes.each do |name, attribute|
    object.send "#{name.underscore}=", attribute.value unless attribute.namespace
  end

  element.children.each do |child|
    object.objects.push parse(child, object) unless child.is_a? Nokogiri::XML::Text
  end

  object.parent = parent

  if object.is_a? Error
    object.raise
  end

  object
end

Instance Method Details

#find(name) ⇒ Object

Find the object by the given name.

name - A String or Symbol describing the “name” attribute of an object.



23
24
25
# File 'lib/obix/objects/base.rb', line 23

def find name
  object = objects.find { |o| o.name == name.to_s }
end

#to_nodeObject

Serialize the object as a Nokogiri::XML::Node.



28
29
30
31
32
# File 'lib/obix/objects/base.rb', line 28

def to_node
  Nokogiri::XML::Builder.new do |xml|
    build xml
  end.doc.root
end

#to_sObject

Serialize the object as a human-readable String.



40
41
42
43
44
45
46
# File 'lib/obix/objects/base.rb', line 40

def to_s
  attributes = @attributes.map do |key, value|
    "#{key}: \"#{value}\""
  end.join " "

  "#<#{self.class} #{attributes}>"
end

#to_xmlObject

Serialize the object as an XML String.



35
36
37
# File 'lib/obix/objects/base.rb', line 35

def to_xml
  to_node.document.to_xml
end