Skip to content

Commit acee501

Browse files
Merge pull request rails#42532 from zzak/zzak/35035
Allow any module or class to be converted to JSON in a simple way
2 parents b3dee90 + f186a00 commit acee501

File tree

3 files changed

+14
-0
lines changed

3 files changed

+14
-0
lines changed

activesupport/CHANGELOG.md

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,7 @@
1+
* Allow serializing any module or class to JSON by name
2+
3+
*Tyler Rick*, *Zachary Scott*
4+
15
* Raise `ActiveSupport::EncryptedFile::MissingKeyError` when the
26
`RAILS_MASTER_KEY` environment variable is blank (e.g. `""`).
37

activesupport/lib/active_support/core_ext/object/json.rb

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -49,6 +49,12 @@ def to_json(options = nil)
4949
klass.prepend(ActiveSupport::ToJsonWithActiveSupportEncoder)
5050
end
5151

52+
class Module
53+
def as_json(options = nil) #:nodoc:
54+
name
55+
end
56+
end
57+
5258
class Object
5359
def as_json(options = nil) #:nodoc:
5460
if respond_to?(:to_hash)

activesupport/test/json/encoding_test_cases.rb

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -68,6 +68,10 @@ module EncodingTestCases
6868
[ :this, %("this") ],
6969
[ :"a b", %("a b") ]]
7070

71+
ModuleTests = [[ Module, %("Module") ],
72+
[ Class, %("Class") ],
73+
[ ActiveSupport, %("ActiveSupport") ],
74+
[ ActiveSupport::MessageEncryptor, %("ActiveSupport::MessageEncryptor") ]]
7175
ObjectTests = [[ Foo.new(1, 2), %({\"a\":1,\"b\":2}) ]]
7276
HashlikeTests = [[ Hashlike.new, %({\"bar\":\"world\",\"foo\":\"hello\"}) ]]
7377
StructTests = [[ MyStruct.new(:foo, "bar"), %({\"name\":\"foo\",\"value\":\"bar\"}) ],

0 commit comments

Comments
 (0)