aboutsummaryrefslogtreecommitdiffstats
path: root/activesupport
diff options
context:
space:
mode:
Diffstat (limited to 'activesupport')
-rw-r--r--activesupport/lib/active_support/json/encoding.rb19
-rw-r--r--activesupport/test/ordered_hash_test.rb7
2 files changed, 21 insertions, 5 deletions
diff --git a/activesupport/lib/active_support/json/encoding.rb b/activesupport/lib/active_support/json/encoding.rb
index 02c233595d..dd94315111 100644
--- a/activesupport/lib/active_support/json/encoding.rb
+++ b/activesupport/lib/active_support/json/encoding.rb
@@ -128,12 +128,21 @@ module ActiveSupport
end
end
-class Object
- # Dumps object in JSON (JavaScript Object Notation). See www.json.org for more info.
- def to_json(options = nil)
- ActiveSupport::JSON.encode(self, options)
- end
+# The JSON gem adds a few modules to Ruby core classes containing :to_json definition, overwriting
+# their default behavior. That said, we need to define the basic to_json method in all of them,
+# otherwise they will always use to_json gem implementation, which is backwards incompatible in
+# several cases (for instance, the JSON implementation for Hash does not work) with inheritance
+# and consequently classes as ActiveSupport::OrderedHash cannot be serialized to json.
+[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)
+ ActiveSupport::JSON.encode(self, options)
+ end
+ RUBY
+end
+class Object
def as_json(options = nil) #:nodoc:
if respond_to?(:to_hash)
to_hash
diff --git a/activesupport/test/ordered_hash_test.rb b/activesupport/test/ordered_hash_test.rb
index dca5c5d0c0..f3d2ec0286 100644
--- a/activesupport/test/ordered_hash_test.rb
+++ b/activesupport/test/ordered_hash_test.rb
@@ -1,4 +1,5 @@
require 'abstract_unit'
+require 'active_support/json'
class OrderedHashTest < Test::Unit::TestCase
def setup
@@ -185,6 +186,12 @@ class OrderedHashTest < Test::Unit::TestCase
assert @ordered_hash.inspect.include?(@hash.inspect)
end
+ def test_json
+ ordered_hash = ActiveSupport::OrderedHash[:foo, :bar]
+ hash = Hash[:foo, :bar]
+ assert_equal ordered_hash.to_json, hash.to_json
+ end
+
def test_alternate_initialization_with_splat
alternate = ActiveSupport::OrderedHash[1,2,3,4]
assert_kind_of ActiveSupport::OrderedHash, alternate