Skip to content

Commit

Permalink
Support dumping custom AR type to JSON
Browse files Browse the repository at this point in the history
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.
  • Loading branch information
lest committed Apr 21, 2017
1 parent f630487 commit e601cde
Show file tree
Hide file tree
Showing 2 changed files with 9 additions and 2 deletions.
4 changes: 4 additions & 0 deletions lib/enumerize/activerecord.rb
Original file line number Diff line number Diff line change
Expand Up @@ -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
7 changes: 5 additions & 2 deletions test/activerecord_test.rb
Original file line number Diff line number Diff line change
Expand Up @@ -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

0 comments on commit e601cde

Please sign in to comment.