2007-09-20 19:22:30 -04:00
|
|
|
module ActiveRecord #:nodoc:
|
2010-06-16 13:52:35 -04:00
|
|
|
# = Active Record Serialization
|
2007-09-20 19:22:30 -04:00
|
|
|
module Serialization
|
2009-08-13 23:27:09 -04:00
|
|
|
extend ActiveSupport::Concern
|
|
|
|
include ActiveModel::Serializers::JSON
|
|
|
|
|
|
|
|
def serializable_hash(options = nil)
|
|
|
|
options ||= {}
|
|
|
|
|
|
|
|
options[:except] = Array.wrap(options[:except]).map { |n| n.to_s }
|
|
|
|
options[:except] |= Array.wrap(self.class.inheritance_column)
|
|
|
|
|
|
|
|
hash = super(options)
|
|
|
|
|
|
|
|
serializable_add_includes(options) do |association, records, opts|
|
|
|
|
hash[association] = records.is_a?(Enumerable) ?
|
|
|
|
records.map { |r| r.serializable_hash(opts) } :
|
|
|
|
records.serializable_hash(opts)
|
2007-09-20 19:22:30 -04:00
|
|
|
end
|
|
|
|
|
2009-08-13 23:27:09 -04:00
|
|
|
hash
|
|
|
|
end
|
|
|
|
|
|
|
|
private
|
2008-05-02 09:45:23 -04:00
|
|
|
# Add associations specified via the <tt>:includes</tt> option.
|
2010-06-16 13:52:35 -04:00
|
|
|
#
|
2007-09-28 10:07:23 -04:00
|
|
|
# Expects a block that takes as arguments:
|
|
|
|
# +association+ - name of the association
|
|
|
|
# +records+ - the association record(s) to be serialized
|
|
|
|
# +opts+ - options for the association records
|
2009-08-13 23:27:09 -04:00
|
|
|
def serializable_add_includes(options = {})
|
|
|
|
return unless include_associations = options.delete(:include)
|
2007-09-28 10:07:23 -04:00
|
|
|
|
2009-08-13 23:27:09 -04:00
|
|
|
base_only_or_except = { :except => options[:except],
|
|
|
|
:only => options[:only] }
|
|
|
|
|
|
|
|
include_has_options = include_associations.is_a?(Hash)
|
|
|
|
associations = include_has_options ? include_associations.keys : Array.wrap(include_associations)
|
2007-09-28 10:07:23 -04:00
|
|
|
|
2009-08-13 23:27:09 -04:00
|
|
|
for association in associations
|
|
|
|
records = case self.class.reflect_on_association(association).macro
|
|
|
|
when :has_many, :has_and_belongs_to_many
|
|
|
|
send(association).to_a
|
|
|
|
when :has_one, :belongs_to
|
|
|
|
send(association)
|
|
|
|
end
|
2009-05-13 04:10:37 -04:00
|
|
|
|
2009-08-13 23:27:09 -04:00
|
|
|
unless records.nil?
|
|
|
|
association_options = include_has_options ? include_associations[association] : base_only_or_except
|
|
|
|
opts = options.merge(association_options)
|
|
|
|
yield(association, records, opts)
|
|
|
|
end
|
2007-09-20 19:22:30 -04:00
|
|
|
end
|
2009-05-13 04:10:37 -04:00
|
|
|
|
2009-08-13 23:27:09 -04:00
|
|
|
options[:include] = include_associations
|
2007-09-20 19:22:30 -04:00
|
|
|
end
|
|
|
|
end
|
|
|
|
end
|
|
|
|
|
|
|
|
require 'active_record/serializers/xml_serializer'
|