lib/active_model/serializers/json.rb in activemodel-3.1.12 vs lib/active_model/serializers/json.rb in activemodel-3.2.0.rc1
- old
+ new
@@ -13,11 +13,11 @@
class_attribute :include_root_in_json
self.include_root_in_json = true
end
- # Returns a JSON string representing the model. Some configuration can be
+ # Returns a hash representing the model. Some configuration can be
# passed through +options+.
#
# The option <tt>include_root_in_json</tt> controls the top-level behavior
# of +as_json+. If true (the default) +as_json+ will emit a single root
# node named after the object's type. For example:
@@ -30,14 +30,21 @@
# ActiveRecord::Base.include_root_in_json = false
# user.as_json
# # => {"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:
#
- # Without any +options+, the returned JSON string will include all the model's
+ # 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 Hash will include all the model's
# attributes. For example:
#
# user = User.find(1)
# user.as_json
# # => {"id": 1, "name": "Konata Izumi", "age": 16,
@@ -77,24 +84,23 @@
# "created_at": "2006/08/01", "awesome": true,
# "posts": [{"comments": [{"body": "1st post!"}, {"body": "Second!"}],
# "title": "Welcome to the weblog"},
# {"comments": [{"body": "Don't think too hard"}],
# "title": "So I was thinking"}]}
-
def as_json(options = nil)
- hash = serializable_hash(options)
-
- if include_root_in_json
- custom_root = options && options[:root]
- hash = { custom_root || self.class.model_name.element => hash }
+ root = include_root_in_json
+ root = options[:root] if options.try(:key?, :root)
+ if root
+ root = self.class.model_name.element if root == true
+ { root => serializable_hash(options) }
+ else
+ serializable_hash(options)
end
-
- 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
end
end