lib/active_model/serializers/json.rb in activemodel-3.0.pre vs lib/active_model/serializers/json.rb in activemodel-3.0.0.rc

- old
+ new

@@ -1,30 +1,30 @@ require 'active_support/json' -require 'active_support/core_ext/class/attribute_accessors' +require 'active_support/core_ext/class/attribute' module ActiveModel + # == Active Model JSON Serializer module Serializers module JSON extend ActiveSupport::Concern include ActiveModel::Serialization included do extend ActiveModel::Naming - cattr_accessor :include_root_in_json, :instance_writer => false + class_attribute :include_root_in_json + self.include_root_in_json = true end - # Returns a JSON string representing the model. Some configuration is - # available through +options+. + # Returns a JSON string representing the model. Some configuration can be + # passed through +options+. # - # The option <tt>ActiveRecord::Base.include_root_in_json</tt> controls the - # top-level behavior of to_json. In a new Rails application, it is set to - # <tt>true</tt> in initializers/new_rails_defaults.rb. When it is <tt>true</tt>, - # to_json will emit a single root node named after the object's type. For example: + # The option <tt>ActiveModel::Base.include_root_in_json</tt> controls the + # top-level behavior of <tt>to_json</tt>. It is <tt>true</tt> by default. When it is <tt>true</tt>, + # <tt>to_json</tt> will emit a single root node named after the object's type. For example: # # konata = User.find(1) - # ActiveRecord::Base.include_root_in_json = true # konata.to_json # # => { "user": {"id": 1, "name": "Konata Izumi", "age": 16, # "created_at": "2006/08/01", "awesome": true} } # # ActiveRecord::Base.include_root_in_json = false @@ -79,19 +79,25 @@ # "title": "Welcome to the weblog"}, # {"comments": [{"body": "Don't think too hard"}], # "title": "So I was thinking"}]} def encode_json(encoder) hash = serializable_hash(encoder.options) - hash = { self.class.model_name.element => hash } if include_root_in_json + if include_root_in_json + custom_root = encoder.options && encoder.options[:root] + hash = { custom_root || self.class.model_name.element => hash } + end + ActiveSupport::JSON.encode(hash) end def as_json(options = nil) self end def from_json(json) - self.attributes = ActiveSupport::JSON.decode(json) + hash = ActiveSupport::JSON.decode(json) + hash = hash.values.first if include_root_in_json + self.attributes = hash self end end end end