Module: HappyMapper

Defined in:
lib/happymapper.rb,
lib/happymapper/item.rb,
lib/happymapper/element.rb,
lib/happymapper/version.rb,
lib/happymapper/attribute.rb

Defined Under Namespace

Modules: ClassMethods Classes: Attribute, Element, Item

Constant Summary collapse

DEFAULT_NS =
"happymapper"
Version =
'0.3.3'

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.included(base) ⇒ Object



16
17
18
19
20
21
# File 'lib/happymapper.rb', line 16

def self.included(base)
  base.instance_variable_set("@attributes", {})
  base.instance_variable_set("@elements", {})
  base.send :attr_accessor,  :raw_xml
  base.extend ClassMethods
end

Instance Method Details

#_dump(depth) ⇒ Object

Define _load and _dump to allow Marshaling of HappyMapper objects. Note that this isn’t as efficient as a binary data store could be, but such is the nature of XML.



212
213
214
# File 'lib/happymapper.rb', line 212

def _dump(depth)
  @raw_xml || self.to_xml
end

#to_xmlObject



23
24
25
26
27
# File 'lib/happymapper.rb', line 23

def to_xml
  doc = LibXML::XML::Document.new
  doc.root = to_xml_node
  doc.to_s
end

#to_xml_node(root_node = nil) ⇒ Object



29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
# File 'lib/happymapper.rb', line 29

def to_xml_node(root_node = nil)
  node = XML::Node.new(self.class.tag_name)
  root_node ||= node
  # add namespace to node and to root_element if not already set
  if self.class.namespace_url
    if root_node
      namespace_object = root_node.namespaces.find_by_href(self.class.namespace_url)
      namespace_object ||= XML::Namespace.new root_node, self.class.namespace, self.class.namespace_url
      node.namespaces.namespace = namespace_object
    end
  end
  # serialize elements
  self.class.elements.each do |e|
    if e.options[:single] == false
      self.send("#{e.method_name}").each do |array_element|
        node << e.to_xml_node(array_element,root_node)
      end
    else
      element_value = self.send("#{e.method_name}")
      node << e.to_xml_node(element_value,root_node) unless element_value.nil?
    end
  end
  # serialize attributes
  self.class.attributes.each do |a|
    attribute_value = self.send("#{a.method_name}")
    node.attributes[a.tag] = attribute_value.to_s unless attribute_value.nil? 
  end
  node
end