From 91945f02c814645b83e4dc1ac3ac834ceba3c290 Mon Sep 17 00:00:00 2001 From: Matthew Robertson Date: Fri, 20 Jul 2012 15:18:30 -0700 Subject: [PATCH] Added a section to the README about defining custom attributes by overriding `serializable_hash` --- README.markdown | 31 +++++++++++++++++++++++++++++++ 1 file changed, 31 insertions(+) diff --git a/README.markdown b/README.markdown index 5fab7d2d..5ccaa222 100644 --- a/README.markdown +++ b/README.markdown @@ -107,6 +107,37 @@ class PostSerializer < ActiveModel::Serializer end ``` +## Custom Attributes + +If you would like customize your JSON to include things beyond the simple +attributes of the model, you can override its `serializable_hash` method +to return anything you need. For example: + +```ruby +class Person < ActiveRecord::Base + + def full_name + "#{first_name} #{last_name}" + end + + def serializable_hash options = nil + hash = super(options) + hash["full_name"] = full_name + hash + end + +end +``` + +The attributes returned by `serializable_hash` are then available in your serializer +as usual: + +```ruby +class PersonSerializer < ActiveModel::Serializer + attributes :first_name, :last_name, :full_name +end +``` + ## Associations For specified associations, the serializer will look up the association and