Skip to content

Commit

Permalink
Merge pull request #42532 from zzak/zzak/35035
Browse files Browse the repository at this point in the history
Allow any module or class to be converted to JSON in a simple way
  • Loading branch information
guilleiguaran committed Jun 24, 2021
2 parents b3dee90 + f186a00 commit acee501
Show file tree
Hide file tree
Showing 3 changed files with 14 additions and 0 deletions.
4 changes: 4 additions & 0 deletions activesupport/CHANGELOG.md
@@ -1,3 +1,7 @@
* Allow serializing any module or class to JSON by name

*Tyler Rick*, *Zachary Scott*

* Raise `ActiveSupport::EncryptedFile::MissingKeyError` when the
`RAILS_MASTER_KEY` environment variable is blank (e.g. `""`).

Expand Down
6 changes: 6 additions & 0 deletions activesupport/lib/active_support/core_ext/object/json.rb
Expand Up @@ -49,6 +49,12 @@ def to_json(options = nil)
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)
Expand Down
4 changes: 4 additions & 0 deletions activesupport/test/json/encoding_test_cases.rb
Expand Up @@ -68,6 +68,10 @@ module EncodingTestCases
[ :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\"}) ],
Expand Down

0 comments on commit acee501

Please sign in to comment.