From 76fead041f99f712b515f36cb9a7912abe184205 Mon Sep 17 00:00:00 2001 From: Santiago Pastorino Date: Wed, 8 May 2013 13:02:03 -0700 Subject: [PATCH] Make Serializer reuse Serializable --- lib/active_model/serializable.rb | 8 +++---- lib/active_model/serializer.rb | 36 +++++++------------------------- 2 files changed, 12 insertions(+), 32 deletions(-) diff --git a/lib/active_model/serializable.rb b/lib/active_model/serializable.rb index d288df44..07f53ffa 100644 --- a/lib/active_model/serializable.rb +++ b/lib/active_model/serializable.rb @@ -8,11 +8,11 @@ module ActiveModel hash[meta_key] = options[:meta] if options.has_key?(:meta) end - def as_json(*args) - options[:hash] = hash = {} - options[:unique_values] = {} + def as_json(args={}) + if root = args[:root] || options[:root] + options[:hash] = hash = {} + options[:unique_values] = {} - if root = options[:root] hash.merge!(root => serialize) include_meta hash hash diff --git a/lib/active_model/serializer.rb b/lib/active_model/serializer.rb index 281af425..a085775d 100644 --- a/lib/active_model/serializer.rb +++ b/lib/active_model/serializer.rb @@ -1,3 +1,4 @@ +require 'active_model/serializable' require "active_support/core_ext/class/attribute" require "active_support/core_ext/module/anonymous" require 'active_support/dependencies' @@ -40,6 +41,8 @@ module ActiveModel class Serializer extend ActiveSupport::DescendantsTracker + include ActiveModel::Serializable + INCLUDE_METHODS = {} INSTRUMENT = { :serialize => :"serialize.serializer", :associations => :"associations.serializer" } @@ -316,37 +319,14 @@ module ActiveModel @options[:url_options] || {} end - def meta_key - @options[:meta_key].try(:to_sym) || :meta - end - - def include_meta(hash) - hash[meta_key] = @options[:meta] if @options.has_key?(:meta) - end - - def to_json(*args) - if perform_caching? - cache.fetch expand_cache_key([self.class.to_s.underscore, cache_key, 'to-json']) do - super - end - else - super - end - end - # Returns a json representation of the serializable # object including the root. - def as_json(options={}) - if root = options.fetch(:root, @options.fetch(:root, root_name)) - @options[:hash] = hash = {} - @options[:unique_values] = {} + def as_json(args={}) + super(root: args.fetch(:root, options.fetch(:root, root_name))) + end - hash.merge!(root => serializable_hash) - include_meta hash - hash - else - serializable_hash - end + def serialize + serializable_hash end # Returns a hash representation of the serializable