Class: JavabeanXml

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

Overview

TODO : document

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(type_transformations) ⇒ JavabeanXml

Returns a new instance of JavabeanXml.



39
40
41
# File 'lib/javabean_xml.rb', line 39

def initialize type_transformations
  @type_transformations = type_transformations
end

Class Method Details

.default_transformationsObject



8
9
10
11
12
13
14
15
16
17
18
# File 'lib/javabean_xml.rb', line 8

def self.default_transformations
  Hash.new { |hash, key|
    lambda { |value, properties|
      {
        :class => key,
        :value => value,
        :properties => properties
      }.delete_if { |k,v| v.nil? || v.respond_to?(:empty?) && v.empty? }
    }
  }
end

.from_xml(xml, type_transformations = {}) ⇒ Object



20
21
22
23
24
25
26
27
28
29
# File 'lib/javabean_xml.rb', line 20

def self.from_xml xml, type_transformations = {}
  nodes = Nokogiri::XML(xml).xpath("/java/object")
  # clean out all empty text-nodes to simplify parsing
  nodes.xpath("//text()").each do |text_node|
    if text_node.content.strip.empty?
      text_node.remove
    end
  end
  JavabeanXml.new(default_transformations.merge(type_transformations)).parse(nodes)
end

.to_xml(object, type_transformations = {}) ⇒ Object



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

def self.to_xml object, type_transformations = {}
  xml = Builder::XmlMarkup.new #:indent => 2
  xml.instruct! :xml, :version=>"1.0", :encoding=>"UTF-8"
  xml.java :version => "1.6.0_26", :class => "java.beans.XMLDecoder" do
    JavabeanXml.new(type_transformations).to_xml(object, xml)
  end
end

Instance Method Details

#parse(node) ⇒ Object



43
44
45
46
47
48
49
50
51
52
53
54
# File 'lib/javabean_xml.rb', line 43

def parse node
  if node.is_a? Nokogiri::XML::NodeSet
    raise "structure error" if node.length != 1
    node = node.first
  end
  case node.name
  when "object"
    parse_object node
  else
    parse_value node
  end
end

#to_xml(object, xml) ⇒ Object



56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
# File 'lib/javabean_xml.rb', line 56

def to_xml object, xml
  if object.is_a? Hash
    case object[:class]
    when Symbol
      to_value_xml object, xml
    else
      to_object_xml object, xml
    end
  else
    # puts "#{object.inspect} (#{object.class})"
    # puts " -- #{@type_transformations.keys.inspect}"
    transformation = @type_transformations[object.class]
    raise "No transformation registered for #{object.class}" unless transformation
    to_xml transformation[object], xml
  end
end