module ActiveEntity::Typecasting

Offers explicit type conversion. This depends ‘ActiveEntity::Accessor#defined_attributes`.

Public Instance Methods

cast() click to toggle source

Try to cast attribute values. When fails to cast, ignores error and left attribute value as original one.

@return [nil]

# File lib/active_entity/typecasting.rb, line 25
def cast
  defined_attributes.each do |name, attr|
    value = public_send(name)
    next if value.nil?

    begin
      casted = attr.cast!(value)
      public_send("#{name}=", casted)
    rescue ActiveEntity::CastError
    end
  end
  nil
end
cast!() click to toggle source

Try to cast attribute values. When fails to cast, raises the error and rollbacks all values.

@return [nil] @raise [ActiveEntity::CastError]

# File lib/active_entity/typecasting.rb, line 10
def cast!
  casted_values = defined_attributes.map do |name, attr|
    value = public_send(name)
    next [name, nil] if value.nil?
    [name, attr.cast!(value)]
  end

  casted_values.each {|name, casted| public_send("#{name}=", casted) }
  nil
end