aboutsummaryrefslogtreecommitdiffstats
path: root/activemodel/lib/active_model
diff options
context:
space:
mode:
authorJoe Fiorini <joe@joefiorini.com>2011-07-01 22:48:11 -0400
committerJoe Fiorini <joe@joefiorini.com>2011-07-01 23:00:13 -0400
commitac5e6911536b0532498df5f650fc2d172087e174 (patch)
tree5448f786c5719ff176f9d11cb8a71764e71b711f /activemodel/lib/active_model
parent36d289ad242c4c8da74eed35baeb21cdffcbe907 (diff)
downloadrails-ac5e6911536b0532498df5f650fc2d172087e174.tar.gz
rails-ac5e6911536b0532498df5f650fc2d172087e174.tar.bz2
rails-ac5e6911536b0532498df5f650fc2d172087e174.zip
Enable passing root: false to #to_json
Diffstat (limited to 'activemodel/lib/active_model')
-rw-r--r--activemodel/lib/active_model/serializers/json.rb22
1 files changed, 17 insertions, 5 deletions
diff --git a/activemodel/lib/active_model/serializers/json.rb b/activemodel/lib/active_model/serializers/json.rb
index 0405705b35..4fbccd7419 100644
--- a/activemodel/lib/active_model/serializers/json.rb
+++ b/activemodel/lib/active_model/serializers/json.rb
@@ -32,8 +32,15 @@ module ActiveModel
# # => {"id": 1, "name": "Konata Izumi", "age": 16,
# "created_at": "2006/08/01", "awesome": true}
#
- # The remainder of the examples in this section assume +include_root_in_json+
- # is false.
+ # This behavior can also be achieved by setting the <tt>:root</tt> option to +false+ as in:
+ #
+ # user = User.find(1)
+ # user.as_json(root: false)
+ # # => {"id": 1, "name": "Konata Izumi", "age": 16,
+ # "created_at": "2006/08/01", "awesome": true}
+ #
+ # The remainder of the examples in this section assume include_root_in_json is set to
+ # <tt>false</tt>.
#
# Without any +options+, the returned JSON string will include all the model's
# attributes. For example:
@@ -83,7 +90,12 @@ module ActiveModel
def as_json(options = nil)
hash = serializable_hash(options)
- if include_root_in_json
+ include_root = include_root_in_json
+ if options.try(:key?, :root)
+ include_root = options[:root]
+ end
+
+ if include_root
custom_root = options && options[:root]
hash = { custom_root || self.class.model_name.element => hash }
end
@@ -91,9 +103,9 @@ module ActiveModel
hash
end
- def from_json(json)
+ def from_json(json, include_root=include_root_in_json)
hash = ActiveSupport::JSON.decode(json)
- hash = hash.values.first if include_root_in_json
+ hash = hash.values.first if include_root
self.attributes = hash
self
end