Welcome to the "trac"-ing site of soap4r!
[soap4r] [httpclient] [openpgp4u] [pkcs1] [logger] [csv] [vtr]

root/trunk/sample/marshal/customfactory.rb

Revision 1843, 2.0 kB (checked in by nahi, 1 year ago)
  • reorganize sampless
Line 
1 require 'soap/marshal'
2 include SOAP
3
4 class DummyStruct
5   include Enumerable
6
7   QName = XSD::QName.new(nil, 'DummyStruct')
8
9   def initialize(hash = nil)
10     @hash = {}
11     @hash.update(hash) if hash
12   end
13
14   def [](key)
15     @hash[key]
16   end
17
18   def []=(key, value)
19     @hash[key] = value
20   end
21
22   def each
23     @hash.each do |key, value|
24       yield(key, value)
25     end
26   end
27 end
28
29 class DummyStructFactory
30   def obj2soap(soap_class, obj, info, map)
31     unless obj.is_a?(DummyStruct)
32       return nil
33     end
34     soap_obj = soap_class.new(DummyStruct::QName)
35     obj.each do |key, value|
36       soap_obj[key] = SOAPString.new(value.to_s)
37     end
38     soap_obj
39   end
40
41   def soap2obj(obj_class, node, info, map)
42     unless node.type == DummyStruct::QName
43       return false
44     end
45     obj = obj_class.new
46     node.each do |key, value|
47       obj[key] = value.data
48     end
49     return true, obj
50   end
51 end
52
53 class ExplicitTypedArrayFactory < SOAP::Mapping::Factory
54   def obj2soap(soap_class, obj, info, map)
55     unless obj.respond_to?(:arytype)
56       return nil
57     end
58     soap_obj = soap_class.new(ValueArrayName, 1, obj.arytype)
59     mark_marshalled_obj(obj, soap_obj)
60     obj.each do |item|
61       soap_obj.add(Mapping._obj2soap(item, map))
62     end
63     soap_obj
64   end
65
66   # let default TypedArrayFactory handle that.
67   def soap2obj(obj_class, node, info, map)
68     return false
69   end
70 end
71
72 map = Mapping::Registry.new
73 map.set(DummyStruct, SOAPStruct, DummyStructFactory.new)
74 map.set(Array, SOAPArray, ExplicitTypedArrayFactory.new)
75
76 puts
77 puts "== DummyStruct =="
78 puts
79
80 obj = DummyStruct.new('family' => 'Na', 'given' => 'Hi')
81 puts marshalledstring = SOAPMarshal.marshal(obj, map)
82 p SOAPMarshal.unmarshal(marshalledstring, map)
83
84 puts
85 puts "== Custom array =="
86 puts
87
88 obj1 = [1, 2, 3]
89 obj2 = [4, 5, 6]
90 def obj1.arytype
91   XSD::XSDInt::Type
92 end
93
94 puts marshalledstring = SOAPMarshal.marshal(obj1, map)
95 p SOAPMarshal.unmarshal(marshalledstring, map)
96 puts marshalledstring = SOAPMarshal.marshal(obj2, map)
97 p SOAPMarshal.unmarshal(marshalledstring, map)
Note: See TracBrowser for help on using the browser.