From e601cdef5d103ba42d902dfcf8731b3f0e8f4b14 Mon Sep 17 00:00:00 2001 From: Sergey Nartimov Date: Sat, 8 Apr 2017 21:14:22 +0300 Subject: [PATCH] Support dumping custom AR type to JSON There are libraries that dump SQL queries to JSON. In case a record is created or updated, query bound attributes reference a custom AR type for enumerized attributes. So it needs to support dumping to JSON. --- lib/enumerize/activerecord.rb | 4 ++++ test/activerecord_test.rb | 7 +++++-- 2 files changed, 9 insertions(+), 2 deletions(-) diff --git a/lib/enumerize/activerecord.rb b/lib/enumerize/activerecord.rb index 2085f894..f9c09f30 100644 --- a/lib/enumerize/activerecord.rb +++ b/lib/enumerize/activerecord.rb @@ -86,6 +86,10 @@ def deserialize(value) end alias type_cast_from_database deserialize + + def as_json(options = nil) + {attr: @attr.name, subtype: @subtype}.as_json(options) + end end end end diff --git a/test/activerecord_test.rb b/test/activerecord_test.rb index f24f2a44..bd1b1419 100644 --- a/test/activerecord_test.rb +++ b/test/activerecord_test.rb @@ -507,11 +507,14 @@ class InterestsRequiredUser < User end it 'supports AR types serialization' do - User.delete_all - type = User.type_for_attribute('status') type.must_be_instance_of Enumerize::ActiveRecordSupport::Type serialized = type.serialize('blocked') serialized.must_equal 2 end + + it 'has AR type itself JSON serializable' do + type = User.type_for_attribute('status') + type.as_json['attr'].must_equal 'status' + end end