From ac5e6911536b0532498df5f650fc2d172087e174 Mon Sep 17 00:00:00 2001 From: Joe Fiorini Date: Fri, 1 Jul 2011 22:48:11 -0400 Subject: Enable passing root: false to #to_json --- activemodel/lib/active_model/serializers/json.rb | 22 +++++++++++++++++----- 1 file changed, 17 insertions(+), 5 deletions(-) (limited to 'activemodel/lib/active_model/serializers/json.rb') 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 :root 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 + # false. # # 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 -- cgit v1.2.3