module Resourceful::Serialize

This module contains mixin modules used to implement the object serialization used for the Builder#publish method. They can also be used to get serialized representations of objects in other contexts.

Serialization makes use of duck typing. Each class that can be serialized (just Array and ActiveRecord::Base by default) implements the serialize and to_serializable methods. These methods are implemented differently by the different classes, but the semantics of the implementations are consistent, so they can be used consistently.

to_serializable returns an object that can be directly serialized with a call to to_xml, to_yaml, or to_json. This object is either a hash or an array, and all the elements are either values, like strings and integers, or other serializable objects. This is useful for getting a model into a simple data structure format. The attributes argument uses the same semantics as the :attributes option for Builder#publish. For example:

c = Cake.new(:flavor => 'chocolate', :text => 'Happy birthday, Chris!')
c.recipient = User.new(:name => 'Chris', :password => 'not very secure')
c.to_serializable [
    :flavor, :text,
    :recipient => :name
  ]

This would return the Ruby hash

{ :flavor => 'chocolate', :text => 'Happy birthday, Chris!',
  :user => {:name => 'Chris'} }

serialize takes a format (:xml, :yaml, or :json - see New Formats below) and a hash of options. The only option currently recognized is :attributes, which has the same semantics as the :attributes option for Builder#publish. serialize returns a string containing the target serialized in the given format. For example:

c = CandyBag.new(:title => 'jellybag')
c.candies << Candy.new(:type => 'jellybean', :flavor => 'root beer')
c.candies << Candy.new(:type => 'jellybean', :flavor => 'pear')
c.candies << Candy.new(:type => 'licorice',  :flavor => 'anisey')
c.serialize :xml, :attributes => [:title, {:candies => [:type, :flavor]}]

This would return a Ruby string containing

<?xml version="1.0" encoding="UTF-8"?>
<candy-bag>
  <title>jellybag</title>
  <candies>
    <candy>
      <type>jellybean</type>
      <flavor>root beer</flavor>
    </candy>
    <candy>
      <type>jellybean</type>
      <flavor>pear</flavor>
    </candy>
    <candy>
      <type>licorice</type>
      <flavor>anisey</flavor>
    </candy>
  </candies>
</candy-bag>