From cb40ae38c1f650846570ad9e3c1b047797e879f6 Mon Sep 17 00:00:00 2001 From: Tyler Rick Date: Wed, 23 Jan 2019 15:07:16 -0800 Subject: [PATCH] Allow any module or class to be converted to JSON in a simple way --- activesupport/lib/active_support/core_ext/object/json.rb | 6 ++++++ activesupport/test/json/encoding_test_cases.rb | 4 ++++ 2 files changed, 10 insertions(+) diff --git a/activesupport/lib/active_support/core_ext/object/json.rb b/activesupport/lib/active_support/core_ext/object/json.rb index 8ba694266d..75fae96dc6 100644 --- a/activesupport/lib/active_support/core_ext/object/json.rb +++ b/activesupport/lib/active_support/core_ext/object/json.rb @@ -49,6 +49,12 @@ end klass.prepend(ActiveSupport::ToJsonWithActiveSupportEncoder) end +class Module + def as_json(options = nil) #:nodoc: + name + end +end + class Object def as_json(options = nil) #:nodoc: if respond_to?(:to_hash) diff --git a/activesupport/test/json/encoding_test_cases.rb b/activesupport/test/json/encoding_test_cases.rb index daf662051a..662e30c68c 100644 --- a/activesupport/test/json/encoding_test_cases.rb +++ b/activesupport/test/json/encoding_test_cases.rb @@ -68,6 +68,10 @@ module JSONTest [ :this, %("this") ], [ :"a b", %("a b") ]] + ModuleTests = [[ Module, %("Module") ], + [ Class, %("Class") ], + [ ActiveSupport, %("ActiveSupport") ], + [ ActiveSupport::MessageEncryptor, %("ActiveSupport::MessageEncryptor") ]] ObjectTests = [[ Foo.new(1, 2), %({\"a\":1,\"b\":2}) ]] HashlikeTests = [[ Hashlike.new, %({\"bar\":\"world\",\"foo\":\"hello\"}) ]] StructTests = [[ MyStruct.new(:foo, "bar"), %({\"name\":\"foo\",\"value\":\"bar\"}) ],