From 19814df40d171b2ed83875a36d7361881ccf2e70 Mon Sep 17 00:00:00 2001 From: Mikel Lindsaar Date: Sun, 17 Jan 2010 20:14:14 +1100 Subject: [PATCH] Adding documentation for ActiveModel::Serialization --- activemodel/README | 14 ++++- activemodel/lib/active_model/serialization.rb | 58 +++++++++++++++++++ .../lib/active_model/serializers/xml.rb | 4 +- 3 files changed, 73 insertions(+), 3 deletions(-) diff --git a/activemodel/README b/activemodel/README index 27121d2c03..95d1c63f75 100644 --- a/activemodel/README +++ b/activemodel/README @@ -141,4 +141,16 @@ functionality from the following modules: functions. {Learn more}[link:classes/ActiveModel/Observer.html] - \ No newline at end of file + +* Making your object serializable + + ActiveModel::Serialization provides a standard interface for your object + to provide to_json or to_xml serialization... + + s = SerialPerson.new + s.serializable_hash # => {"name"=>nil} + s.to_json # => "{\"name\":null}" + s.to_xml # => "\n 'nil'} + # end + # + # end + # + # Which would provide you with: + # + # person = Person.new + # person.serializable_hash # => {"name"=>nil} + # person.name = "Bob" + # person.serializable_hash # => {"name"=>"Bob"} + # + # You need to declare some sort of attributes hash which contains the attributes + # you want to serialize and their current value. + # + # Most of the time though, you will want to include the JSON or XML + # serializations. Both of these modules automatically include the + # ActiveModel::Serialization module, so there is no need to explicitly + # include it. + # + # So a minimal implementation including XML and JSON would be: + # + # class Person + # + # include ActiveModel::Serializers::JSON + # include ActiveModel::Serializers::Xml + # + # attr_accessor :name + # + # def attributes + # @attributes ||= {'name' => 'nil'} + # end + # + # end + # + # Which would provide you with: + # + # person = Person.new + # person.serializable_hash # => {"name"=>nil} + # person.to_json # => "{\"name\":null}" + # person.to_xml # => "\n {"name"=>"Bob"} + # person.to_json # => "{\"name\":\"Bob\"}" + # person.to_xml # => "\n:except takes precedence over :only. If :only is not set + # To replicate the behavior in ActiveRecord#attributes, :except + # takes precedence over :only. If :only is not set # for a N level model but is set for the N+1 level models, # then because :except is set to a default value, the second # level model can have both :except and :only set. So if