aboutsummaryrefslogtreecommitdiffstats
path: root/activerecord/lib
diff options
context:
space:
mode:
authorRick Olson <technoweenie@gmail.com>2008-04-01 20:09:45 +0000
committerRick Olson <technoweenie@gmail.com>2008-04-01 20:09:45 +0000
commitd450ac4459165e3af6e45798a6afeac1876f3bc4 (patch)
treef555ffd09f7d79fde29824b658cc6e278fcf46ca /activerecord/lib
parent6a74360f972c75c70b64e3b6f51bb7a64681e2e3 (diff)
downloadrails-d450ac4459165e3af6e45798a6afeac1876f3bc4.tar.gz
rails-d450ac4459165e3af6e45798a6afeac1876f3bc4.tar.bz2
rails-d450ac4459165e3af6e45798a6afeac1876f3bc4.zip
Tweak ActiveRecord::Base#to_json to include a root value in the returned hash: {post: {title: ...}} [rick]
git-svn-id: http://svn-commit.rubyonrails.org/rails/trunk@9202 5ecf4fe2-1ee6-0310-87b1-e25e094e27de
Diffstat (limited to 'activerecord/lib')
-rw-r--r--activerecord/lib/active_record/serializers/json_serializer.rb17
1 files changed, 16 insertions, 1 deletions
diff --git a/activerecord/lib/active_record/serializers/json_serializer.rb b/activerecord/lib/active_record/serializers/json_serializer.rb
index c0a5850d5d..d024adba39 100644
--- a/activerecord/lib/active_record/serializers/json_serializer.rb
+++ b/activerecord/lib/active_record/serializers/json_serializer.rb
@@ -1,5 +1,10 @@
module ActiveRecord #:nodoc:
module Serialization
+ def self.included(base)
+ base.cattr_accessor :include_root_in_json, :instance_writer => false
+ base.extend ClassMethods
+ end
+
# Returns a JSON string representing the model. Some configuration is
# available through +options+.
#
@@ -48,7 +53,11 @@ module ActiveRecord #:nodoc:
# {"comments": [{"body": "Don't think too hard"}],
# "title": "So I was thinking"}]}
def to_json(options = {})
- JsonSerializer.new(self, options).to_s
+ if include_root_in_json
+ "{#{self.class.json_class_name}: #{JsonSerializer.new(self, options).to_s}}"
+ else
+ JsonSerializer.new(self, options).to_s
+ end
end
def from_json(json)
@@ -61,5 +70,11 @@ module ActiveRecord #:nodoc:
serializable_record.to_json
end
end
+
+ module ClassMethods
+ def json_class_name
+ @json_class_name ||= name.demodulize.underscore.inspect
+ end
+ end
end
end