nokogiri-happymapper-deiga 0.5.9

Sign up to get free protection for your applications and to get access to all the features.
Files changed (57) hide show
  1. data/CHANGELOG.md +35 -0
  2. data/README.md +605 -0
  3. data/lib/happymapper.rb +751 -0
  4. data/lib/happymapper/anonymous_mapper.rb +114 -0
  5. data/lib/happymapper/attribute.rb +21 -0
  6. data/lib/happymapper/element.rb +55 -0
  7. data/lib/happymapper/item.rb +160 -0
  8. data/lib/happymapper/supported_types.rb +140 -0
  9. data/lib/happymapper/text_node.rb +8 -0
  10. data/lib/happymapper/version.rb +3 -0
  11. data/spec/attribute_default_value_spec.rb +50 -0
  12. data/spec/attributes_spec.rb +36 -0
  13. data/spec/fixtures/address.xml +9 -0
  14. data/spec/fixtures/ambigous_items.xml +22 -0
  15. data/spec/fixtures/analytics.xml +61 -0
  16. data/spec/fixtures/analytics_profile.xml +127 -0
  17. data/spec/fixtures/atom.xml +19 -0
  18. data/spec/fixtures/commit.xml +52 -0
  19. data/spec/fixtures/current_weather.xml +89 -0
  20. data/spec/fixtures/current_weather_missing_elements.xml +18 -0
  21. data/spec/fixtures/default_namespace_combi.xml +6 -0
  22. data/spec/fixtures/dictionary.xml +20 -0
  23. data/spec/fixtures/family_tree.xml +21 -0
  24. data/spec/fixtures/inagy.xml +85 -0
  25. data/spec/fixtures/lastfm.xml +355 -0
  26. data/spec/fixtures/multiple_namespaces.xml +170 -0
  27. data/spec/fixtures/multiple_primitives.xml +5 -0
  28. data/spec/fixtures/optional_attributes.xml +6 -0
  29. data/spec/fixtures/pita.xml +133 -0
  30. data/spec/fixtures/posts.xml +23 -0
  31. data/spec/fixtures/product_default_namespace.xml +18 -0
  32. data/spec/fixtures/product_no_namespace.xml +10 -0
  33. data/spec/fixtures/product_single_namespace.xml +10 -0
  34. data/spec/fixtures/quarters.xml +19 -0
  35. data/spec/fixtures/radar.xml +21 -0
  36. data/spec/fixtures/set_config_options.xml +3 -0
  37. data/spec/fixtures/statuses.xml +422 -0
  38. data/spec/fixtures/subclass_namespace.xml +50 -0
  39. data/spec/fixtures/wrapper.xml +11 -0
  40. data/spec/happymapper/attribute_spec.rb +12 -0
  41. data/spec/happymapper/element_spec.rb +9 -0
  42. data/spec/happymapper/item_spec.rb +115 -0
  43. data/spec/happymapper/text_node_spec.rb +9 -0
  44. data/spec/happymapper_parse_spec.rb +87 -0
  45. data/spec/happymapper_spec.rb +1116 -0
  46. data/spec/has_many_empty_array_spec.rb +43 -0
  47. data/spec/ignay_spec.rb +95 -0
  48. data/spec/inheritance_spec.rb +107 -0
  49. data/spec/mixed_namespaces_spec.rb +61 -0
  50. data/spec/parse_with_object_to_update_spec.rb +111 -0
  51. data/spec/spec_helper.rb +7 -0
  52. data/spec/to_xml_spec.rb +200 -0
  53. data/spec/to_xml_with_namespaces_spec.rb +196 -0
  54. data/spec/wilcard_tag_name_spec.rb +96 -0
  55. data/spec/wrap_spec.rb +82 -0
  56. data/spec/xpath_spec.rb +89 -0
  57. metadata +231 -0
@@ -0,0 +1,751 @@
1
+ require 'nokogiri'
2
+ require 'date'
3
+ require 'time'
4
+ require 'happymapper/anonymous_mapper'
5
+
6
+ module HappyMapper
7
+ class Boolean; end
8
+ class XmlContent; end
9
+
10
+ extend AnonymousMapper
11
+
12
+ DEFAULT_NS = "happymapper"
13
+
14
+ def self.included(base)
15
+ if !(base.superclass <= HappyMapper)
16
+ base.instance_eval do
17
+ @attributes = {}
18
+ @elements = {}
19
+ @order = []
20
+ @registered_namespaces = {}
21
+ @wrapper_anonymous_classes = {}
22
+ end
23
+ else
24
+ base.instance_eval do
25
+ @attributes =
26
+ superclass.instance_variable_get(:@attributes).dup
27
+ @elements =
28
+ superclass.instance_variable_get(:@elements).dup
29
+ @order =
30
+ superclass.instance_variable_get(:@order).dup
31
+ @registered_namespaces =
32
+ superclass.instance_variable_get(:@registered_namespaces).dup
33
+ @wrapper_anonymous_classes =
34
+ superclass.instance_variable_get(:@wrapper_anonymous_classes).dup
35
+ end
36
+ end
37
+
38
+ base.extend ClassMethods
39
+ end
40
+
41
+ module ClassMethods
42
+
43
+ #
44
+ # The xml has the following attributes defined.
45
+ #
46
+ # @example
47
+ #
48
+ # "<country code='de'>Germany</country>"
49
+ #
50
+ # # definition of the 'code' attribute within the class
51
+ # attribute :code, String
52
+ #
53
+ # @param [Symbol] name the name of the accessor that is created
54
+ # @param [String,Class] type the class name of the name of the class whcih
55
+ # the object will be converted upon parsing
56
+ # @param [Hash] options additional parameters to send to the relationship
57
+ #
58
+ def attribute(name, type, options={})
59
+ attribute = Attribute.new(name, type, options)
60
+ @attributes[name] = attribute
61
+ attr_accessor attribute.method_name.intern
62
+ end
63
+
64
+ #
65
+ # The elements defined through {#attribute}.
66
+ #
67
+ # @return [Array<Attribute>] a list of the attributes defined for this class;
68
+ # an empty array is returned when there have been no attributes defined.
69
+ #
70
+ def attributes
71
+ @attributes.values
72
+ end
73
+
74
+ #
75
+ # Register a namespace that is used to persist the object namespace back to
76
+ # XML.
77
+ #
78
+ # @example
79
+ #
80
+ # register_namespace 'prefix', 'http://www.unicornland.com/prefix'
81
+ #
82
+ # # the output will contain the namespace defined
83
+ #
84
+ # "<outputXML xmlns:prefix="http://www.unicornland.com/prefix">
85
+ # ...
86
+ # </outputXML>"
87
+ #
88
+ # @param [String] namespace the xml prefix
89
+ # @param [String] ns url for the xml namespace
90
+ #
91
+ def register_namespace(namespace, ns)
92
+ @registered_namespaces.merge!({namespace => ns})
93
+ end
94
+
95
+ #
96
+ # An element defined in the XML that is parsed.
97
+ #
98
+ # @example
99
+ #
100
+ # "<address location='home'>
101
+ # <city>Oldenburg</city>
102
+ # </address>"
103
+ #
104
+ # # definition of the 'city' element within the class
105
+ #
106
+ # element :city, String
107
+ #
108
+ # @param [Symbol] name the name of the accessor that is created
109
+ # @param [String,Class] type the class name of the name of the class whcih
110
+ # the object will be converted upon parsing
111
+ # @param [Hash] options additional parameters to send to the relationship
112
+ #
113
+ def element(name, type, options={})
114
+ element = Element.new(name, type, options)
115
+ @elements[name] = element
116
+ @order << name unless @order.include? name
117
+ attr_accessor element.method_name.intern
118
+ end
119
+
120
+ #
121
+ # The elements defined through {#element}, {#has_one}, and {#has_many}.
122
+ #
123
+ # @return [Array<Element>] a list of the elements contained defined for this
124
+ # class; an empty array is returned when there have been no elements
125
+ # defined.
126
+ #
127
+ def elements
128
+ @order.map { |name| @elements[name] }
129
+ end
130
+
131
+ #
132
+ # The value stored in the text node of the current element.
133
+ #
134
+ # @example
135
+ #
136
+ # "<firstName>Michael Jackson</firstName>"
137
+ #
138
+ # # definition of the 'firstName' text node within the class
139
+ #
140
+ # content :first_name, String
141
+ #
142
+ # @param [Symbol] name the name of the accessor that is created
143
+ # @param [String,Class] type the class name of the name of the class whcih
144
+ # the object will be converted upon parsing. By Default String class will be taken.
145
+ # @param [Hash] options additional parameters to send to the relationship
146
+ #
147
+ def content(name, type=String, options={})
148
+ @content = TextNode.new(name, type, options)
149
+ attr_accessor @content.method_name.intern
150
+ end
151
+
152
+ #
153
+ # Sets the object to have xml content, this will assign the XML contents
154
+ # that are parsed to the attribute accessor xml_content. The object will
155
+ # respond to the method #xml_content and will return the XML data that
156
+ # it has parsed.
157
+ #
158
+ def has_xml_content
159
+ attr_accessor :xml_content
160
+ end
161
+
162
+ #
163
+ # The object has one of these elements in the XML. If there are multiple,
164
+ # the last one will be set to this value.
165
+ #
166
+ # @param [Symbol] name the name of the accessor that is created
167
+ # @param [String,Class] type the class name of the name of the class whcih
168
+ # the object will be converted upon parsing
169
+ # @param [Hash] options additional parameters to send to the relationship
170
+ #
171
+ # @see #element
172
+ #
173
+ def has_one(name, type, options={})
174
+ element name, type, {:single => true}.merge(options)
175
+ end
176
+
177
+ #
178
+ # The object has many of these elements in the XML.
179
+ #
180
+ # @param [Symbol] name the name of accessor that is created
181
+ # @param [String,Class] type the class name or the name of the class which
182
+ # the object will be converted upon parsing.
183
+ # @param [Hash] options additional parameters to send to the relationship
184
+ #
185
+ # @see #element
186
+ #
187
+ def has_many(name, type, options={})
188
+ element name, type, {:single => false}.merge(options)
189
+ end
190
+
191
+ #
192
+ # Specify a namespace if a node and all its children are all namespaced
193
+ # elements. This is simpler than passing the :namespace option to each
194
+ # defined element.
195
+ #
196
+ # @param [String] namespace the namespace to set as default for the class
197
+ # element.
198
+ #
199
+ def namespace(namespace = nil)
200
+ @namespace = namespace if namespace
201
+ @namespace
202
+ end
203
+
204
+ #
205
+ # @param [String] new_tag_name the name for the tag
206
+ #
207
+ def tag(new_tag_name)
208
+ @tag_name = new_tag_name.to_s unless new_tag_name.nil? || new_tag_name.to_s.empty?
209
+ end
210
+
211
+ #
212
+ # The name of the tag
213
+ #
214
+ # @return [String] the name of the tag as a string, downcased
215
+ #
216
+ def tag_name
217
+ @tag_name ||= to_s.split('::')[-1].downcase
218
+ end
219
+
220
+ # There is an XML tag that needs to be known for parsing and should be generated
221
+ # during a to_xml. But it doesn't need to be a class and the contained elements should
222
+ # be made available on the parent class
223
+ #
224
+ # @param [String] name the name of the element that is just a place holder
225
+ # @param [Proc] blk the element definitions inside the place holder tag
226
+ #
227
+ def wrap(name, &blk)
228
+ # Get an anonymous HappyMapper that has 'name' as its tag and defined
229
+ # in '&blk'. Then save that to a class instance variable for later use
230
+ wrapper = AnonymousWrapperClassFactory.get(name, &blk)
231
+ @wrapper_anonymous_classes[wrapper.inspect] = wrapper
232
+
233
+ # Create getter/setter for each element and attribute defined on the anonymous HappyMapper
234
+ # onto this class. They get/set the value by passing thru to the anonymous class.
235
+ passthrus = wrapper.attributes + wrapper.elements
236
+ passthrus.each do |item|
237
+ class_eval %{
238
+ def #{item.method_name}
239
+ @#{name} ||= self.class.instance_variable_get('@wrapper_anonymous_classes')['#{wrapper.inspect}'].new
240
+ @#{name}.#{item.method_name}
241
+ end
242
+ def #{item.method_name}=(value)
243
+ @#{name} ||= self.class.instance_variable_get('@wrapper_anonymous_classes')['#{wrapper.inspect}'].new
244
+ @#{name}.#{item.method_name} = value
245
+ end
246
+ }
247
+ end
248
+
249
+ has_one name, wrapper
250
+ end
251
+
252
+ # The callback defined through {.with_nokogiri_config}.
253
+ #
254
+ # @return [Proc] the proc to pass to Nokogiri to setup parse options. nil if empty.
255
+ #
256
+ def nokogiri_config_callback
257
+ @nokogiri_config_callback
258
+ end
259
+
260
+ # Register a config callback according to the block Nokogori expects when calling Nokogiri::XML::Document.parse().
261
+ # See http://nokogiri.org/Nokogiri/XML/Document.html#method-c-parse
262
+ #
263
+ # @param [Proc] the proc to pass to Nokogiri to setup parse options
264
+ #
265
+ def with_nokogiri_config(&blk)
266
+ @nokogiri_config_callback = blk
267
+ end
268
+
269
+ #
270
+ # @param [Nokogiri::XML::Node,Nokogiri:XML::Document,String] xml the XML
271
+ # contents to convert into Object.
272
+ # @param [Hash] options additional information for parsing. :single => true
273
+ # if requesting a single object, otherwise it defaults to retuning an
274
+ # array of multiple items. :xpath information where to start the parsing
275
+ # :namespace is the namespace to use for additional information.
276
+ #
277
+ def parse(xml, options = {})
278
+
279
+ # create a local copy of the objects namespace value for this parse execution
280
+ namespace = @namespace
281
+
282
+ # If the XML specified is an Node then we have what we need.
283
+ if xml.is_a?(Nokogiri::XML::Node) && !xml.is_a?(Nokogiri::XML::Document)
284
+ node = xml
285
+ else
286
+
287
+ # If xml is an XML document select the root node of the document
288
+ if xml.is_a?(Nokogiri::XML::Document)
289
+ node = xml.root
290
+ else
291
+
292
+ # Attempt to parse the xml value with Nokogiri XML as a document
293
+ # and select the root element
294
+ xml = Nokogiri::XML(
295
+ xml, nil, nil,
296
+ Nokogiri::XML::ParseOptions::STRICT,
297
+ &nokogiri_config_callback
298
+ )
299
+ node = xml.root
300
+ end
301
+
302
+ # if the node name is equal to the tag name then the we are parsing the
303
+ # root element and that is important to record so that we can apply
304
+ # the correct xpath on the elements of this document.
305
+
306
+ root = node.name == tag_name
307
+ end
308
+
309
+ # if any namespaces have been provied then we should capture those and then
310
+ # merge them with any namespaces found on the xml node and merge all that
311
+ # with any namespaces that have been registered on the object
312
+
313
+ namespaces = options[:namespaces] || {}
314
+ namespaces = namespaces.merge(xml.collect_namespaces) if xml.respond_to?(:collect_namespaces)
315
+ namespaces = namespaces.merge(@registered_namespaces)
316
+
317
+ # if a namespace has been provided then set the current namespace to it
318
+ # or set the default namespace to the one defined under 'xmlns'
319
+ # or set the default namespace to the namespace that matches 'happymapper's
320
+
321
+ if options[:namespace]
322
+ namespace = options[:namespace]
323
+ elsif namespaces.has_key?("xmlns")
324
+ namespace ||= DEFAULT_NS
325
+ namespaces[DEFAULT_NS] = namespaces.delete("xmlns")
326
+ elsif namespaces.has_key?(DEFAULT_NS)
327
+ namespace ||= DEFAULT_NS
328
+ end
329
+
330
+ # from the options grab any nodes present and if none are present then
331
+ # perform the following to find the nodes for the given class
332
+
333
+ nodes = options.fetch(:nodes) do
334
+
335
+ # when at the root use the xpath '/' otherwise use a more gready './/'
336
+ # unless an xpath has been specified, which should overwrite default
337
+ # and finally attach the current namespace if one has been defined
338
+ #
339
+
340
+ xpath = (root ? '/' : './/')
341
+ xpath = options[:xpath].to_s.sub(/([^\/])$/, '\1/') if options[:xpath]
342
+ xpath += "#{namespace}:" if namespace
343
+
344
+ nodes = []
345
+
346
+ # when finding nodes, do it in this order:
347
+ # 1. specified tag if one has been provided
348
+ # 2. name of element
349
+ # 3. tag_name (derived from class name by default)
350
+
351
+ # If a tag has been provided we need to search for it.
352
+
353
+ if options.key?(:tag)
354
+ begin
355
+ nodes = node.xpath(xpath + options[:tag].to_s, namespaces)
356
+ rescue
357
+ # This exception takes place when the namespace is often not found
358
+ # and we should continue on with the empty array of nodes.
359
+ end
360
+ else
361
+
362
+ # This is the default case when no tag value is provided.
363
+ # First we use the name of the element `items` in `has_many items`
364
+ # Second we use the tag name which is the name of the class cleaned up
365
+
366
+ [options[:name], tag_name].compact.each do |xpath_ext|
367
+ begin
368
+ nodes = node.xpath(xpath + xpath_ext.to_s, namespaces)
369
+ rescue
370
+ break
371
+ # This exception takes place when the namespace is often not found
372
+ # and we should continue with the empty array of nodes or keep looking
373
+ end
374
+ break if nodes && !nodes.empty?
375
+ end
376
+
377
+ end
378
+
379
+ nodes
380
+ end
381
+
382
+ # Nothing matching found, we can go ahead and return
383
+ return ( ( options[:single] || root ) ? nil : [] ) if nodes.size == 0
384
+
385
+ # If the :limit option has been specified then we are going to slice
386
+ # our node results by that amount to allow us the ability to deal with
387
+ # a large result set of data.
388
+
389
+ limit = options[:in_groups_of] || nodes.size
390
+
391
+ # If the limit of 0 has been specified then the user obviously wants
392
+ # none of the nodes that we are serving within this batch of nodes.
393
+
394
+ return [] if limit == 0
395
+
396
+ collection = []
397
+
398
+ nodes.each_slice(limit) do |slice|
399
+
400
+ part = slice.map do |n|
401
+
402
+ # If an existing HappyMapper object is provided, update it with the
403
+ # values from the xml being parsed. Otherwise, create a new object
404
+
405
+ obj = options[:update] ? options[:update] : new
406
+
407
+ attributes.each do |attr|
408
+ value = attr.from_xml_node(n, namespace, namespaces)
409
+ value = attr.default if value.nil?
410
+ obj.send("#{attr.method_name}=", value)
411
+ end
412
+
413
+ elements.each do |elem|
414
+ obj.send("#{elem.method_name}=",elem.from_xml_node(n, namespace, namespaces))
415
+ end
416
+
417
+ if @content
418
+ obj.send("#{@content.method_name}=",@content.from_xml_node(n, namespace, namespaces))
419
+ end
420
+
421
+ # If the HappyMapper class has the method #xml_value=,
422
+ # attr_writer :xml_value, or attr_accessor :xml_value then we want to
423
+ # assign the current xml that we just parsed to the xml_value
424
+
425
+ if obj.respond_to?('xml_value=')
426
+ n.namespaces.each {|name,path| n[name] = path }
427
+ obj.xml_value = n.to_xml
428
+ end
429
+
430
+ # If the HappyMapper class has the method #xml_content=,
431
+ # attr_write :xml_content, or attr_accessor :xml_content then we want to
432
+ # assign the child xml that we just parsed to the xml_content
433
+
434
+ if obj.respond_to?('xml_content=')
435
+ n = n.children if n.respond_to?(:children)
436
+ obj.xml_content = n.to_xml
437
+ end
438
+
439
+ # collect the object that we have created
440
+
441
+ obj
442
+ end
443
+
444
+ # If a block has been provided and the user has requested that the objects
445
+ # be handled in groups then we should yield the slice of the objects to them
446
+ # otherwise continue to lump them together
447
+
448
+ if block_given? and options[:in_groups_of]
449
+ yield part
450
+ else
451
+ collection += part
452
+ end
453
+
454
+ end
455
+
456
+ # per http://libxml.rubyforge.org/rdoc/classes/LibXML/XML/Document.html#M000354
457
+ nodes = nil
458
+
459
+ # If the :single option has been specified or we are at the root element
460
+ # then we are going to return the first item in the collection. Otherwise
461
+ # the return response is going to be an entire array of items.
462
+
463
+ if options[:single] or root
464
+ collection.first
465
+ else
466
+ collection
467
+ end
468
+ end
469
+ end
470
+
471
+ # Set all attributes with a default to their default values
472
+ def initialize
473
+ super
474
+ self.class.attributes.reject {|attr| attr.default.nil?}.each do |attr|
475
+ send("#{attr.method_name}=", attr.default)
476
+ end
477
+ end
478
+
479
+ #
480
+ # Create an xml representation of the specified class based on defined
481
+ # HappyMapper elements and attributes. The method is defined in a way
482
+ # that it can be called recursively by classes that are also HappyMapper
483
+ # classes, allowg for the composition of classes.
484
+ #
485
+ # @param [Nokogiri::XML::Builder] builder an instance of the XML builder which
486
+ # is being used when called recursively.
487
+ # @param [String] default_namespace the name of the namespace which is the
488
+ # default for the xml being produced; this is specified by the element
489
+ # declaration when calling #to_xml recursively.
490
+ # @param [String] tag_from_parent the xml tag to use on the element when being
491
+ # called recursively. This lets the parent doc define its own structure.
492
+ # Otherwise the element uses the tag it has defined for itself. Should only
493
+ # apply when calling a child HappyMapper element.
494
+ #
495
+ # @return [String,Nokogiri::XML::Builder] return XML representation of the
496
+ # HappyMapper object; when called recursively this is going to return
497
+ # and Nokogiri::XML::Builder object.
498
+ #
499
+ def to_xml(builder = nil,default_namespace = nil,tag_from_parent = nil)
500
+
501
+ #
502
+ # If to_xml has been called without a passed in builder instance that
503
+ # means we are going to return xml output. When it has been called with
504
+ # a builder instance that means we most likely being called recursively
505
+ # and will return the end product as a builder instance.
506
+ #
507
+ unless builder
508
+ write_out_to_xml = true
509
+ builder = Nokogiri::XML::Builder.new
510
+ end
511
+
512
+ #
513
+ # Find the attributes for the class and collect them into an array
514
+ # that will be placed into a Hash structure
515
+ #
516
+ attributes = self.class.attributes.collect do |attribute|
517
+
518
+ #
519
+ # If an attribute is marked as read_only then we want to ignore the attribute
520
+ # when it comes to saving the xml document; so we wiill not go into any of
521
+ # the below process
522
+ #
523
+ unless attribute.options[:read_only]
524
+
525
+ value = send(attribute.method_name)
526
+ value = nil if value == attribute.default
527
+
528
+ #
529
+ # If the attribute defines an on_save lambda/proc or value that maps to
530
+ # a method that the class has defined, then call it with the value as a
531
+ # parameter.
532
+ #
533
+ if on_save_action = attribute.options[:on_save]
534
+ if on_save_action.is_a?(Proc)
535
+ value = on_save_action.call(value)
536
+ elsif respond_to?(on_save_action)
537
+ value = send(on_save_action,value)
538
+ end
539
+ end
540
+
541
+ #
542
+ # Attributes that have a nil value should be ignored unless they explicitly
543
+ # state that they should be expressed in the output.
544
+ #
545
+ if not value.nil? || attribute.options[:state_when_nil]
546
+ attribute_namespace = attribute.options[:namespace] || default_namespace
547
+ [ "#{attribute_namespace ? "#{attribute_namespace}:" : ""}#{attribute.tag}", value ]
548
+ else
549
+ []
550
+ end
551
+
552
+ else
553
+ []
554
+ end
555
+
556
+ end.flatten
557
+
558
+ attributes = Hash[ *attributes ]
559
+
560
+ #
561
+ # Create a tag in the builder that matches the class's tag name unless a tag was passed
562
+ # in a recursive call from the parent doc. Then append
563
+ # any attributes to the element that were defined above.
564
+ #
565
+ builder.send("#{tag_from_parent || self.class.tag_name}_",attributes) do |xml|
566
+
567
+ #
568
+ # Add all the registered namespaces to the root element.
569
+ # When this is called recurisvely by composed classes the namespaces
570
+ # are still added to the root element
571
+ #
572
+ # However, we do not want to add the namespace if the namespace is 'xmlns'
573
+ # which means that it is the default namesapce of the code.
574
+ #
575
+ if self.class.instance_variable_get('@registered_namespaces') && builder.doc.root
576
+ self.class.instance_variable_get('@registered_namespaces').each_pair do |name,href|
577
+ name = nil if name == "xmlns"
578
+ builder.doc.root.add_namespace(name,href)
579
+ end
580
+ end
581
+
582
+ #
583
+ # If the object we are persisting has a namespace declaration we will want
584
+ # to use that namespace or we will use the default namespace.
585
+ # When neither are specifed we are simply using whatever is default to the
586
+ # builder
587
+ #
588
+ if self.class.respond_to?(:namespace) && self.class.namespace
589
+ xml.parent.namespace = builder.doc.root.namespace_definitions.find { |x| x.prefix == self.class.namespace }
590
+ elsif default_namespace
591
+ xml.parent.namespace = builder.doc.root.namespace_definitions.find { |x| x.prefix == default_namespace }
592
+ end
593
+
594
+
595
+ #
596
+ # When a content has been defined we add the resulting value
597
+ # the output xml
598
+ #
599
+ if content = self.class.instance_variable_get('@content')
600
+
601
+ unless content.options[:read_only]
602
+ text_accessor = content.tag || content.name
603
+ value = send(text_accessor)
604
+
605
+ if on_save_action = content.options[:on_save]
606
+ if on_save_action.is_a?(Proc)
607
+ value = on_save_action.call(value)
608
+ elsif respond_to?(on_save_action)
609
+ value = send(on_save_action,value)
610
+ end
611
+ end
612
+
613
+ builder.text(value)
614
+ end
615
+
616
+ end
617
+
618
+ #
619
+ # for every define element (i.e. has_one, has_many, element) we are
620
+ # going to persist each one
621
+ #
622
+ self.class.elements.each do |element|
623
+
624
+ #
625
+ # If an element is marked as read only do not consider at all when
626
+ # saving to XML.
627
+ #
628
+ unless element.options[:read_only]
629
+
630
+ tag = element.tag || element.name
631
+
632
+ #
633
+ # The value to store is the result of the method call to the element,
634
+ # by default this is simply utilizing the attr_accessor defined. However,
635
+ # this allows for this method to be overridden
636
+ #
637
+ value = send(element.name)
638
+
639
+ #
640
+ # If the element defines an on_save lambda/proc then we will call that
641
+ # operation on the specified value. This allows for operations to be
642
+ # performed to convert the value to a specific value to be saved to the xml.
643
+ #
644
+ if on_save_action = element.options[:on_save]
645
+ if on_save_action.is_a?(Proc)
646
+ value = on_save_action.call(value)
647
+ elsif respond_to?(on_save_action)
648
+ value = send(on_save_action,value)
649
+ end
650
+ end
651
+
652
+ #
653
+ # Normally a nil value would be ignored, however if specified then
654
+ # an empty element will be written to the xml
655
+ #
656
+ if value.nil? && element.options[:single] && element.options[:state_when_nil]
657
+ xml.send("#{tag}_","")
658
+ end
659
+
660
+ #
661
+ # To allow for us to treat both groups of items and singular items
662
+ # equally we wrap the value and treat it as an array.
663
+ #
664
+ if value.nil?
665
+ values = []
666
+ elsif value.respond_to?(:to_ary) && !element.options[:single]
667
+ values = value.to_ary
668
+ else
669
+ values = [value]
670
+ end
671
+
672
+ values.each do |item|
673
+
674
+ if item.is_a?(HappyMapper)
675
+
676
+ #
677
+ # Other items are convertable to xml through the xml builder
678
+ # process should have their contents retrieved and attached
679
+ # to the builder structure
680
+ #
681
+ item.to_xml(xml,element.options[:namespace],element.options[:tag] || nil)
682
+
683
+ elsif !item.nil?
684
+
685
+ item_namespace = element.options[:namespace] || self.class.namespace || default_namespace
686
+
687
+ #
688
+ # When a value exists we should append the value for the tag
689
+ #
690
+ if item_namespace
691
+ xml[item_namespace].send("#{tag}_",item.to_s)
692
+ else
693
+ xml.send("#{tag}_",item.to_s)
694
+ end
695
+
696
+ else
697
+
698
+ #
699
+ # Normally a nil value would be ignored, however if specified then
700
+ # an empty element will be written to the xml
701
+ #
702
+ xml.send("#{tag}_","") if element.options[:state_when_nil]
703
+
704
+ end
705
+
706
+ end
707
+
708
+ end
709
+ end
710
+
711
+ end
712
+
713
+ # Write out to XML, this value was set above, based on whether or not an XML
714
+ # builder object was passed to it as a parameter. When there was no parameter
715
+ # we assume we are at the root level of the #to_xml call and want the actual
716
+ # xml generated from the object. If an XML builder instance was specified
717
+ # then we assume that has been called recursively to generate a larger
718
+ # XML document.
719
+ write_out_to_xml ? builder.to_xml : builder
720
+
721
+ end
722
+
723
+ # Parse the xml and update this instance. This does not update instances
724
+ # of HappyMappers that are children of this object. New instances will be
725
+ # created for any HappyMapper children of this object.
726
+ #
727
+ # Params and return are the same as the class parse() method above.
728
+ def parse(xml, options = {})
729
+ self.class.parse(xml, options.merge!(:update => self))
730
+ end
731
+
732
+ private
733
+
734
+ # Factory for creating anonmyous HappyMappers
735
+ class AnonymousWrapperClassFactory
736
+ def self.get(name, &blk)
737
+ Class.new do
738
+ include HappyMapper
739
+ tag name
740
+ instance_eval &blk
741
+ end
742
+ end
743
+ end
744
+
745
+ end
746
+
747
+ require 'happymapper/supported_types'
748
+ require 'happymapper/item'
749
+ require 'happymapper/attribute'
750
+ require 'happymapper/element'
751
+ require 'happymapper/text_node'