class Paquito::SerializedColumn

Public Class Methods

new(coder, type = nil, attribute_name: nil) click to toggle source
# File lib/paquito/serialized_column.rb, line 5
def initialize(coder, type = nil, attribute_name: nil)
  @coder = coder
  @type = type
  @attribute_name = attribute_name || "Attribute"
  check_arity_of_constructor
  @default_value = type&.new
end

Public Instance Methods

dump(object) click to toggle source
# File lib/paquito/serialized_column.rb, line 25
def dump(object)
  return if object.nil? || object == @default_value

  check_type(object)
  @coder.dump(object)
end
load(payload) click to toggle source
# File lib/paquito/serialized_column.rb, line 17
def load(payload)
  return @type&.new if payload.nil?

  object = @coder.load(payload)
  check_type(object)
  object || @type&.new
end
object_class() click to toggle source
# File lib/paquito/serialized_column.rb, line 13
def object_class
  @type || Object
end

Private Instance Methods

check_arity_of_constructor() click to toggle source
# File lib/paquito/serialized_column.rb, line 34
def check_arity_of_constructor
  load(nil)
rescue ArgumentError
  raise ArgumentError,
    "Cannot serialize #{object_class}. Classes passed to `serialize` must have a 0 argument constructor."
end
check_type(object) click to toggle source
# File lib/paquito/serialized_column.rb, line 45
def check_type(object)
  unless @type.nil? || object.is_a?(@type) || object.nil?
    raise ActiveRecord::SerializationTypeMismatch, "#{@attribute_name} was supposed to be a #{object_class}, " \
      "but was a #{object.class}. -- #{object.inspect}"
  end
end
default_value?(object) click to toggle source
# File lib/paquito/serialized_column.rb, line 41
def default_value?(object)
  object == @type&.new
end