Sha256: 0a52703def64873e290b1c5d635bf5fcc39ac4bdd975c65abe97dd48024354fe

Contents?: true

Size: 1.64 KB

Versions: 1

Compression:

Stored size: 1.64 KB

Contents

require 'simple_mapper/support/bliss_serializer'

module SimpleMapper
  module XmlFormat
    def self.included(base)
      base.extend ClassMethods
    end

    def self.mime_type_headers
      {'Accept' => 'application/xml', 'Content-type' => 'application/xml'}
    end

    def to_xml
      Serialize.object_to_xml(self, :key_name => 'self').to_s
    end

    module ClassMethods
      # This assumes a standard xml format:
      #   <person attribute="">
      #     <another_att>value</another_att>
      #   </person>
      # And for a collection of objects:
      #   <people>
      #     <person attribute="">
      #       <another_att>value 1</another_att>
      #     </person>
      #     <person attribute="">
      #       <another_att>value 2</another_att>
      #     </person>
      #   </people>
      def from_xml(xml)
        doc = Serialize.hash_from_xml(xml)
        # doc could include a single 'model' element, or a 'models' wrapper around several.
        puts "Top-level XML key(s): #{doc.keys.inspect}" if @debug
        key = doc.keys.first
        if doc[key].keys.uniq == [key.singularize] && doc[key][key.singularize].is_a?(Array)
          puts "Several objects returned under key '#{key}'/'#{key.singularize}':" if @debug
          doc[key][key.singularize].collect do |e|
            puts "Obj: #{e.inspect}" if @debug
            Object.module_eval("::#{key.singularize.camelize}", __FILE__, __LINE__).new(e)
          end
        else # top-level must be single object
          Object.module_eval("::#{key.singularize.camelize}", __FILE__, __LINE__).new(Serialize.hash_from_xml(xml)[self.name.underscore])
        end
      end
    end
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
simplemapper-0.0.1 lib/simple_mapper/formats/xml_format.rb