aboutsummaryrefslogtreecommitdiffstats
path: root/activemodel/lib/active_model/serializers/json.rb
diff options
context:
space:
mode:
Diffstat (limited to 'activemodel/lib/active_model/serializers/json.rb')
-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