= dm-serializer

== Overview

dm-serializer allows DataMapper models and collections to be serialized to a variety of formats (currently JSON, XML, YAML and CSV).

== How it works

One method is added to each model/collection for each serialization type - <tt>to_json</tt>, <tt>to_xml</tt>, <tt>to_yaml</tt>, and <tt>to_csv</tt>. With the exception of <tt>to_csv</tt>, all of these methods share the same interface. <tt>to_json</tt> will be used for examples. Any method specific behaviour is documented in its own section below.

  require 'dm-serializer'

  class Cow
    include DataMapper::Resource

    property :id,   Integer, :key => true
    property :name, String

    def description
      "A Cow"
    end
  end

  cow = Cow.create(
    :id    => 1,
    :name  => "Berta"
  )

  cow.to_json                      # => { "id": 1, "name": "Berta" }
  cow.to_json(:only    => [:name]) # => { "name": "Berta" }
  cow.to_json(:exclude => [:id])   # => { "name": "Berta" }
  cow.to_json(:methods => [:desc]) # => { "id": 1, "name": "Berta", "desc": "A Cow" }

You can include associations by passing the association accessor the <tt>:methods</tt> option.

If you want to only load a particular serialization method, that's cool, you can do that:

  require 'dm-serializer/to_json'

== to_xml

<tt>to_xml</tt> supports some extra options to allow you to override the element names

  cow.to_xml(:element_name => 'bovine') # => <bovine><id>1</id><name>Berta</name></bovine>
  cows.to_xml(:collection_element_name => 'kine')   # => <kine><bovine><id>1</id><name>Berta</name></bovine></kine>


If you would like a nice speed boost (~5x), require <tt>libxml</tt> or <tt>nokogiri</tt> before <tt>dm-serializer</tt>, and that library will be used rather than REXML.

== to_csv

<tt>to_csv</tt> currently doesn't support any options yet. It will in the future. It will not support serializing child associations.


== Arrays, Hashes, and other core classes

<tt>dm-serializer</tt> only adds serialization methods to DataMapper objects and collections, however some libraries used (json, yaml) add methods to core classes, such as <tt>Array</tt>. Note that passing <tt>dm-serializer</tt> options (such as <tt>:only</tt>) to these methods is *not supported*.

  Cow.all.to_a.to_yaml(:only => 'name') # WILL NOT WORK


== Beware

If you go spelunking through the code you will find other undocumented options. Use at your own risk, I plan on removing or changing these in the near future.
