Changeset 9202
- Timestamp:
- 04/01/08 20:09:45 (1 year ago)
- Files:
-
- trunk/activerecord/CHANGELOG (modified) (1 diff)
- trunk/activerecord/lib/active_record/serializers/json_serializer.rb (modified) (3 diffs)
- trunk/activerecord/test/cases/json_serialization_test.rb (modified) (2 diffs)
Legend:
- Unmodified
- Added
- Removed
- Modified
- Copied
- Moved
trunk/activerecord/CHANGELOG
r9200 r9202 1 1 *SVN* 2 3 * Tweak ActiveRecord::Base#to_json to include a root value in the returned hash: {"post": {"title": ...}} [rick] 4 5 Post.find(1).to_json # => {"title": ...} 6 config.active_record.include_root_in_json = true 7 Post.find(1).to_json # => {"post": {"title": ...}} 2 8 3 9 * Add efficient #include? to AssociationCollection (for has_many/has_many :through/habtm). [stopdropandrew] trunk/activerecord/lib/active_record/serializers/json_serializer.rb
r9093 r9202 1 1 module ActiveRecord #:nodoc: 2 2 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 3 8 # Returns a JSON string representing the model. Some configuration is 4 9 # available through +options+. … … 49 54 # "title": "So I was thinking"}]} 50 55 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 52 61 end 53 62 … … 62 71 end 63 72 end 73 74 module ClassMethods 75 def json_class_name 76 @json_class_name ||= name.demodulize.underscore.inspect 77 end 78 end 64 79 end 65 80 end trunk/activerecord/test/cases/json_serialization_test.rb
r8681 r9202 8 8 9 9 class JsonSerializationTest < ActiveRecord::TestCase 10 class NamespacedContact < Contact 11 column :name, :string 12 end 13 10 14 def setup 11 15 @contact = Contact.new( … … 17 21 :preferences => { :shows => 'anime' } 18 22 ) 23 end 24 25 def test_should_demodulize_root_in_json 26 NamespacedContact.include_root_in_json = true 27 @contact = NamespacedContact.new :name => 'whatever' 28 json = @contact.to_json 29 assert_match %r{^\{"namespaced_contact": \{}, json 30 end 31 32 def test_should_include_root_in_json 33 Contact.include_root_in_json = true 34 json = @contact.to_json 35 36 assert_match %r{^\{"contact": \{}, json 37 assert_match %r{"name": "Konata Izumi"}, json 38 assert_match %r{"age": 16}, json 39 assert json.include?(%("created_at": #{ActiveSupport::JSON.encode(Time.utc(2006, 8, 1))})) 40 assert_match %r{"awesome": true}, json 41 assert_match %r{"preferences": \{"shows": "anime"\}}, json 42 ensure 43 Contact.include_root_in_json = false 19 44 end 20 45