Permalink
Browse files

ActiveRecord::Base.include_root_in_json support

Precedence:

1) options[:root] passed to ActiveModel::Serializer
2) 'root' definition in serializer
3) ActiveRecord::Base.include_root_in_json

This gives fine granularity with respect to API responses.
  • Loading branch information...
1 parent 92b1642 commit 049cf62a21b81cab05b83afdac1c66ae008c07d2 @cadwallion committed May 18, 2012
Showing with 12 additions and 2 deletions.
  1. +12 −2 lib/active_model/serializer.rb
@@ -54,6 +54,12 @@ def as_json(*args)
array = serializable_array.map(&:serializable_hash)
+ if Object.const_defined? :ActiveRecord
+ if !ActiveRecord::Base.include_root_in_json
+ return array
+ end
+ end
+
if root = @options[:root]
hash.merge!(root => array)
else
@@ -366,7 +372,7 @@ def root(name)
def inherited(klass) #:nodoc:
return if klass.anonymous?
name = klass.name.demodulize.underscore.sub(/_serializer$/, '')
-
+
klass.class_eval do
alias_method name.to_sym, :object
root name.to_sym unless self._root == false
@@ -388,12 +394,16 @@ def url_options
# object including the root.
def as_json(options=nil)
options ||= {}
+
+ if Object.const_defined?(:ActiveRecord) && _root.nil?
+ _root = false if !ActiveRecord::Base.include_root_in_json
+ end
+
if root = options.fetch(:root, @options.fetch(:root, _root))
@options[:hash] = hash = {}
@options[:unique_values] = {}
hash.merge!(root => serializable_hash)
- hash
else
serializable_hash
end

0 comments on commit 049cf62

Please sign in to comment.