Class: HashType

Inherits:
ActiveModel::Type::Value
  • Object
show all
Defined in:
app/types/hash_type.rb

Overview

Custom ActiveRecord/ActiveModel attribute type that round-trips a
Hash through JSON. Hands the database a JSON string but lets
application code work with a plain Hash.

Instance Method Summary collapse

Instance Method Details

#cast(value) ⇒ Object



6
7
8
# File 'app/types/hash_type.rb', line 6

def cast(value)
  value.is_a?(String) ? JSON.parse(value) : value.to_h
end

#deserialize(value) ⇒ Object



14
15
16
# File 'app/types/hash_type.rb', line 14

def deserialize(value)
  cast(value)
end

#serialize(value) ⇒ Object



10
11
12
# File 'app/types/hash_type.rb', line 10

def serialize(value)
  value.to_json
end