Module: ActiveAttr::Typecasting

Included in:
TypecastedAttributes
Defined in:
lib/active_attr/typecasting.rb,
lib/active_attr/typecasting/boolean.rb,
lib/active_attr/typecasting/date_typecaster.rb,
lib/active_attr/typecasting/float_typecaster.rb,
lib/active_attr/typecasting/object_typecaster.rb,
lib/active_attr/typecasting/string_typecaster.rb,
lib/active_attr/typecasting/boolean_typecaster.rb,
lib/active_attr/typecasting/integer_typecaster.rb,
lib/active_attr/typecasting/date_time_typecaster.rb,
lib/active_attr/typecasting/big_decimal_typecaster.rb,
lib/active_attr/typecasting/unknown_typecaster_error.rb

Overview

Typecasting provides methods to typecast a value to a different type

The following types are supported for typecasting:

  • BigDecimal

  • Boolean

  • Date

  • DateTime

  • Float

  • Integer

  • Object

  • String

Since:

  • 0.5.0

Defined Under Namespace

Classes: BigDecimalTypecaster, Boolean, BooleanTypecaster, DateTimeTypecaster, DateTypecaster, FloatTypecaster, IntegerTypecaster, ObjectTypecaster, StringTypecaster, UnknownTypecasterError

Instance Method Summary collapse

Instance Method Details

#typecast_attribute(typecaster, value) ⇒ Object?

Typecasts a value using a Class

Parameters:

  • typecaster (#call)

    The typecaster to use for typecasting

  • value (Object)

    The value to be typecasted

Returns:

  • (Object, nil)

    The typecasted value or nil if it cannot be typecasted

Raises:

  • (ArgumentError)

Since:

  • 0.5.0



48
49
50
51
52
# File 'lib/active_attr/typecasting.rb', line 48

def typecast_attribute(typecaster, value)
  raise ArgumentError, "a typecaster must be given" unless typecaster.respond_to?(:call)
  return value if value.nil?
  typecaster.call(value)
end

#typecaster_for(type) ⇒ #call?

Resolve a Class to a typecaster

Parameters:

  • type (Class)

    The type to cast to

Returns:

  • (#call, nil)

    The typecaster to use

Since:

  • 0.6.0



61
62
63
64
# File 'lib/active_attr/typecasting.rb', line 61

def typecaster_for(type)
  typecaster = TYPECASTER_MAP[type]
  typecaster.new if typecaster
end