Ruby on Rails | Screencasts | Download | Documentation | Weblog | Community | Source
Show
Ignore:
Timestamp:
04/01/08 20:09:45 (8 months ago)
Author:
rick
Message:

Tweak ActiveRecord::Base#to_json to include a root value in the returned hash: {post: {title: ...}} [rick]

Files:

Legend:

Unmodified
Added
Removed
Modified
Copied
Moved
  • trunk/activerecord/lib/active_record/serializers/json_serializer.rb

    r9093 r9202  
    11module ActiveRecord #:nodoc: 
    22  module Serialization 
     3    def self.included(base) 
     4      base.cattr_accessor :include_root_in_json, :instance_writer => false 
     5      base.extend ClassMethods 
     6    end 
     7 
    38    # Returns a JSON string representing the model. Some configuration is 
    49    # available through +options+. 
     
    4954    #                    "title": "So I was thinking"}]} 
    5055    def to_json(options = {}) 
    51       JsonSerializer.new(self, options).to_s 
     56      if include_root_in_json 
     57        "{#{self.class.json_class_name}: #{JsonSerializer.new(self, options).to_s}}" 
     58      else 
     59        JsonSerializer.new(self, options).to_s 
     60      end 
    5261    end 
    5362 
     
    6271      end 
    6372    end 
     73 
     74    module ClassMethods 
     75      def json_class_name 
     76        @json_class_name ||= name.demodulize.underscore.inspect 
     77      end 
     78    end 
    6479  end 
    6580end