Skip to content

Instantly share code, notes, and snippets.

@AquaGeek
Created May 13, 2011 03:21
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save AquaGeek/969907 to your computer and use it in GitHub Desktop.
Save AquaGeek/969907 to your computer and use it in GitHub Desktop.
Rails Lighthouse ticket #610
From 3a5dd2d63c06f1801518ccdcc902b01bc1cba8f8 Mon Sep 17 00:00:00 2001
From: David Burger <davidjburger@yahoo.com>
Date: Sat, 12 Jul 2008 18:33:01 -1000
Subject: [PATCH] to_json invokes to_json of included associations
---
.../active_record/serializers/json_serializer.rb | 18 +++++++++++++++++-
activerecord/test/cases/json_serialization_test.rb | 11 +++++++++++
2 files changed, 28 insertions(+), 1 deletions(-)
diff --git a/activerecord/lib/active_record/serializers/json_serializer.rb b/activerecord/lib/active_record/serializers/json_serializer.rb
index 419b45d..0540874 100644
--- a/activerecord/lib/active_record/serializers/json_serializer.rb
+++ b/activerecord/lib/active_record/serializers/json_serializer.rb
@@ -66,8 +66,24 @@ module ActiveRecord #:nodoc:
end
class JsonSerializer < ActiveRecord::Serialization::Serializer #:nodoc:
+ def add_associations(association, records, opts, json)
+ if records.is_a?(Enumerable)
+ include_json = ''
+ if !records.empty?
+ include_json = records.map { |record| record.to_json(opts) }.join(', ')
+ end
+ json << "{\"#{association.to_s}\": [#{include_json}]}"
+ else
+ json << "{\"#{association.to_s}\": #{records.to_json(opts)}}"
+ end
+ end
+
def serialize
- serializable_record.to_json
+ include_json = ''
+ add_includes { |association, records, opts| add_associations(association, records, opts, include_json) }
+ include_json.insert(0, ', ') if !include_json.blank?
+ json = serializable_names.inject({}) { |names, name| names[name] = @record.send(name); names }.to_json
+ "#{json[0..-2]}#{include_json}}"
end
end
diff --git a/activerecord/test/cases/json_serialization_test.rb b/activerecord/test/cases/json_serialization_test.rb
index 3446e5e..c9ff597 100644
--- a/activerecord/test/cases/json_serialization_test.rb
+++ b/activerecord/test/cases/json_serialization_test.rb
@@ -202,4 +202,15 @@ class DatabaseConnectedJsonEncodingTest < ActiveRecord::TestCase
assert_equal %({1: {"name": "David"}}), authors_hash.to_json(:only => [1, :name])
end
+
+ def test_should_call_includes_to_json
+ Post.send(:define_method, :to_json) do |options|
+ options.merge!(:only => :title)
+ super
+ end
+ json = @david.to_json(:include => :posts)
+
+ assert json.include?('"title": "Welcome to the weblog"'), json
+ assert !json.include?('"body": "Such a lovely day"'), json
+ end
end
--
1.5.4.3
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment