class StoreModel::Types::One
Implements ActiveModel::Type::Value type for handling an instance of StoreModel::Model
Public Class Methods
new(model_klass)
click to toggle source
Initializes type for model class
@param model_klass [StoreModel::Model] model class to handle
@return [StoreModel::Types::One]
# File lib/store_model/types/one.rb, line 14 def initialize(model_klass) @model_klass = model_klass end
Public Instance Methods
cast_value(value)
click to toggle source
Casts value
from DB or user to StoreModel::Model
instance
@param value [Object] a value to cast
@return StoreModel::Model
# File lib/store_model/types/one.rb, line 30 def cast_value(value) case value when String then decode_and_initialize(value) when Hash then model_instance(value) when @model_klass, nil then value else raise_cast_error(value) end rescue ActiveModel::UnknownAttributeError => e handle_unknown_attribute(value, e) end
serialize(value)
click to toggle source
Casts a value from the ruby type to a type that the database knows how to understand.
@param value [Object] value to serialize
@return [String] serialized value
Calls superclass method
# File lib/store_model/types/one.rb, line 47 def serialize(value) case value when Hash, @model_klass ActiveSupport::JSON.encode(value) else super end end
type()
click to toggle source
Returns type
@return [Symbol]
# File lib/store_model/types/one.rb, line 21 def type :json end
Private Instance Methods
model_instance(value)
click to toggle source
# File lib/store_model/types/one.rb, line 64 def model_instance(value) @model_klass.new(value) end
raise_cast_error(value)
click to toggle source
# File lib/store_model/types/one.rb, line 58 def raise_cast_error(value) raise StoreModel::Types::CastError, "failed casting #{value.inspect}, only String, " \ "Hash or #{@model_klass.name} instances are allowed" end