Module: HappyMapper

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

Defined Under Namespace

Modules: ClassMethods Classes: Attribute, Element, Item, TextNode

Constant Summary collapse

DEFAULT_NS =
"happymapper"

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.included(base) ⇒ Object



12
13
14
15
16
17
18
# File 'lib/happymapper.rb', line 12

def self.included(base)
  base.instance_variable_set("@attributes", {})
  base.instance_variable_set("@elements", {})
  base.instance_variable_set("@registered_namespaces", {})

  base.extend ClassMethods
end

Instance Method Details

#to_xml(builder = nil, default_namespace = nil) ⇒ String, Nokogiri::XML::Builder

Create an xml representation of the specified class based on defined HappyMapper elements and attributes. The method is defined in a way that it can be called recursively by classes that are also HappyMapper classes, allowg for the composition of classes.

Parameters:

  • builder (Nokogiri::XML::Builder) (defaults to: nil)

    an instance of the XML builder which is being used when called recursively.

  • default_namespace (String) (defaults to: nil)

    the name of the namespace which is the default for the xml being produced; this is specified by the element declaration when calling #to_xml recursively.

Returns:

  • (String, Nokogiri::XML::Builder)

    return XML representation of the HappyMapper object; when called recursively this is going to return and Nokogiri::XML::Builder object.



389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
# File 'lib/happymapper.rb', line 389

def to_xml(builder = nil,default_namespace = nil)
  
  #
  # If to_xml has been called without a passed in builder instance that
  # means we are going to return xml output. When it has been called with
  # a builder instance that means we most likely being called recursively
  # and will return the end product as a builder instance. 
  #
  unless builder
    write_out_to_xml = true
    builder = Nokogiri::XML::Builder.new
  end
  
  #
  # Find the attributes for the class and collect them into an array
  # that will be placed into a Hash structure
  #
  attributes = self.class.attributes.collect do |attribute|
    
    #
    # If an attribute is marked as read_only then we want to ignore the attribute
    # when it comes to saving the xml document; so we wiill not go into any of
    # the below process
    # 
    unless attribute.options[:read_only]
    
      value = send(attribute.method_name)
    
      #
      # If the attribute defines an on_save lambda/proc or value that maps to 
      # a method that the class has defined, then call it with the value as a
      # parameter.
      #
      if on_save_action = attribute.options[:on_save]
        if on_save_action.is_a?(Proc)
          value = on_save_action.call(value)
        elsif respond_to?(on_save_action)
          value = send(on_save_action,value)
        end
      end
    
      #
      # Attributes that have a nil value should be ignored unless they explicitly
      # state that they should be expressed in the output.
      #
      if value || attribute.options[:state_when_nil]
        attribute_namespace = attribute.options[:namespace] || default_namespace
        [ "#{attribute_namespace ? "#{attribute_namespace}:" : ""}#{attribute.tag}", value ]
      else
        []
      end
      
    else
      []
    end
    
  end.flatten
  
  attributes = Hash[ *attributes ]

  #
  # Create a tag in the builder that matches the class's tag name and append
  # any attributes to the element that were defined above.
  #
  builder.send("#{self.class.tag_name}_",attributes) do |xml|
    
    #
    # Add all the registered namespaces to the root element.
    # When this is called recurisvely by composed classes the namespaces
    # are still added to the root element
    # 
    # However, we do not want to add the namespace if the namespace is 'xmlns'
    # which means that it is the default namesapce of the code.
    #
    if self.class.instance_variable_get('@registered_namespaces') && builder.doc.root
      self.class.instance_variable_get('@registered_namespaces').each_pair do |name,href|
        name = nil if name == "xmlns"
        builder.doc.root.add_namespace(name,href)
      end
    end
    
    #
    # If the object we are persisting has a namespace declaration we will want
    # to use that namespace or we will use the default namespace.
    # When neither are specifed we are simply using whatever is default to the
    # builder
    #
    if self.class.respond_to?(:namespace) && self.class.namespace
      xml.parent.namespace = builder.doc.root.namespace_definitions.find { |x| x.prefix == self.class.namespace }
    elsif default_namespace
      xml.parent.namespace = builder.doc.root.namespace_definitions.find { |x| x.prefix == default_namespace }
    end

    
    #
    # When a content has been defined we add the resulting value
    # the output xml
    #
    if content = self.class.instance_variable_get('@content')
      
      unless content.options[:read_only]
        text_accessor = content.tag || content.name
        value = send(text_accessor)
      
        if on_save_action = content.options[:on_save]
          if on_save_action.is_a?(Proc)
            value = on_save_action.call(value)
          elsif respond_to?(on_save_action)
            value = send(on_save_action,value)
          end
        end
      
        builder.text(value)
      end
      
    end

    #
    # for every define element (i.e. has_one, has_many, element) we are
    # going to persist each one
    #
    self.class.elements.each do |element|
      
      #
      # If an element is marked as read only do not consider at all when 
      # saving to XML.
      # 
      unless element.options[:read_only]
        
        tag = element.tag || element.name
        
        #
        # The value to store is the result of the method call to the element,
        # by default this is simply utilizing the attr_accessor defined. However,
        # this allows for this method to be overridden
        #
        value = send(element.name)

        #
        # If the element defines an on_save lambda/proc then we will call that
        # operation on the specified value. This allows for operations to be 
        # performed to convert the value to a specific value to be saved to the xml.
        #
        if on_save_action = element.options[:on_save]
          if on_save_action.is_a?(Proc)
            value = on_save_action.call(value)
          elsif respond_to?(on_save_action)
            value = send(on_save_action,value)
          end 
        end

        #
        # Normally a nil value would be ignored, however if specified then
        # an empty element will be written to the xml
        #
        if value.nil? && element.options[:single] && element.options[:state_when_nil]
          xml.send("#{tag}_","")
        end
      
        #
        # To allow for us to treat both groups of items and singular items
        # equally we wrap the value and treat it as an array.
        #
        if value.nil?
          values = []
        elsif value.respond_to?(:to_ary) && !element.options[:single]
          values = value.to_ary
        else
          values = [value]
        end
      
        values.each do |item|

          if item.is_a?(HappyMapper)

            #
            # Other items are convertable to xml through the xml builder
            # process should have their contents retrieved and attached
            # to the builder structure
            #
            item.to_xml(xml,element.options[:namespace])

          elsif item
          
            item_namespace = element.options[:namespace] || default_namespace
          
            #
            # When a value exists we should append the value for the tag
            #
            if item_namespace
              xml[item_namespace].send("#{tag}_",item.to_s)
            else
              xml.send("#{tag}_",item.to_s)
            end

          else

            #
            # Normally a nil value would be ignored, however if specified then
            # an empty element will be written to the xml
            #
            xml.send("#{tag}_","") if element.options[:state_when_nil]

          end

        end
        
      end
    end

  end

  # Write out to XML, this value was set above, based on whether or not an XML
  # builder object was passed to it as a parameter. When there was no parameter
  # we assume we are at the root level of the #to_xml call and want the actual
  # xml generated from the object. If an XML builder instance was specified 
  # then we assume that has been called recursively to generate a larger 
  # XML document.
  write_out_to_xml ? builder.to_xml : builder
  
end