aboutsummaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
authorNicolás Hock Isaza <nhocki@gmail.com>2011-09-29 20:07:19 -0500
committerNicolás Hock Isaza <nhocki@gmail.com>2011-09-29 21:44:23 -0500
commitda914fa35c014b7753e609e25c6a45d3cda11274 (patch)
treeaef75e5afe3ddcd57d3e143981e8125825d3fd1a
parentd2888de5985c7018a5be23d44143ec3c6cef9032 (diff)
downloadrails-da914fa35c014b7753e609e25c6a45d3cda11274.tar.gz
rails-da914fa35c014b7753e609e25c6a45d3cda11274.tar.bz2
rails-da914fa35c014b7753e609e25c6a45d3cda11274.zip
Fixing `as_json` method for ActiveRecord models.
When you've got an AR Model and you override the `as_json` method, you should be able to add default options to the renderer, like this: class User < ActiveRecord::Base def as_json(options = {}) super(options.merge(:except => [:password_digest])) end end This was not possible before this commit. See the added test case.
-rw-r--r--activemodel/test/cases/serializers/json_serialization_test.rb10
-rw-r--r--activesupport/lib/active_support/core_ext/object/to_json.rb2
2 files changed, 11 insertions, 1 deletions
diff --git a/activemodel/test/cases/serializers/json_serialization_test.rb b/activemodel/test/cases/serializers/json_serialization_test.rb
index 40fdcf20ca..a754d610b9 100644
--- a/activemodel/test/cases/serializers/json_serialization_test.rb
+++ b/activemodel/test/cases/serializers/json_serialization_test.rb
@@ -206,4 +206,14 @@ class JsonSerializationTest < ActiveModel::TestCase
assert_no_match %r{"preferences":}, json
end
+ test "custom as_json options should be extendible" do
+ def @contact.as_json(options = {}); super(options.merge(:only => [:name])); end
+ json = @contact.to_json
+
+ assert_match %r{"name":"Konata Izumi"}, json
+ assert_no_match %r{"created_at":#{ActiveSupport::JSON.encode(Time.utc(2006, 8, 1))}}, json
+ assert_no_match %r{"awesome":}, json
+ assert_no_match %r{"preferences":}, json
+ end
+
end
diff --git a/activesupport/lib/active_support/core_ext/object/to_json.rb b/activesupport/lib/active_support/core_ext/object/to_json.rb
index 14ef27340e..82e232070d 100644
--- a/activesupport/lib/active_support/core_ext/object/to_json.rb
+++ b/activesupport/lib/active_support/core_ext/object/to_json.rb
@@ -12,7 +12,7 @@ end
[Object, Array, FalseClass, Float, Hash, Integer, NilClass, String, TrueClass].each do |klass|
klass.class_eval <<-RUBY, __FILE__, __LINE__
# Dumps object in JSON (JavaScript Object Notation). See www.json.org for more info.
- def to_json(options = nil)
+ def to_json(options = {})
ActiveSupport::JSON.encode(self, options)
end
RUBY