Class: JSONColumnCoder
- Inherits:
-
Object
- Object
- JSONColumnCoder
- Defined in:
- app/services/json_column_coder.rb
Instance Attribute Summary collapse
-
#object_class ⇒ Object
Returns the value of attribute object_class.
Instance Method Summary collapse
- #dump(obj) ⇒ Object
-
#initialize(object_class = Object) ⇒ JSONColumnCoder
constructor
A new instance of JSONColumnCoder.
- #load(json) ⇒ Object
Constructor Details
#initialize(object_class = Object) ⇒ JSONColumnCoder
Returns a new instance of JSONColumnCoder.
6 7 8 |
# File 'app/services/json_column_coder.rb', line 6 def initialize(object_class = Object) @object_class = object_class end |
Instance Attribute Details
#object_class ⇒ Object
Returns the value of attribute object_class.
4 5 6 |
# File 'app/services/json_column_coder.rb', line 4 def object_class @object_class end |
Instance Method Details
#dump(obj) ⇒ Object
10 11 12 13 14 15 16 17 18 |
# File 'app/services/json_column_coder.rb', line 10 def dump(obj) return if obj.nil? unless obj.is_a?(object_class) raise ActiveRecord::SerializationTypeMismatch, "Attribute was supposed to be a #{object_class}, but was a #{obj.class}. -- #{obj.inspect}" end JSON.dump obj end |
#load(json) ⇒ Object
20 21 22 23 24 25 26 27 28 29 30 31 32 |
# File 'app/services/json_column_coder.rb', line 20 def load(json) return object_class.new if object_class != Object && json.nil? return json unless json.is_a?(String) obj = JSON.load(json) unless obj.is_a?(object_class) || obj.nil? raise ActiveRecord::SerializationTypeMismatch, "Attribute was supposed to be a #{object_class}, but was a #{obj.class}" end obj ||= object_class.new if object_class != Object obj end |