module ActiveAttr::TypecastedAttributes
TypecastedAttributes
allows types to be declared for your attributes
Types are declared by passing the :type option to the attribute class method. After a type is declared, attribute readers will convert any assigned attribute value to the declared type. If the assigned value cannot be cast, nil will be returned instead. You can access the original assigned value using the before_type_cast methods.
See {Typecasting} for the currently supported types.
@example Usage
class Person include ActiveAttr::TypecastedAttributes attribute :age, :type => Integer end person = Person.new person.age = "29" person.age #=> 29 person.age_before_type_cast #=> "29"
@since 0.5.0
Public Instance Methods
Read the raw attribute value
@example Reading a raw age value
person.age = "29" person.attribute_before_type_cast(:age) #=> "29"
@param [String, Symbol, to_s] name Attribute name
@return [Object, nil] The attribute value before typecasting
@since 0.5.0
# File lib/active_attr/typecasted_attributes.rb, line 48 def attribute_before_type_cast(name) @attributes ||= {} @attributes[name.to_s] end
Private Instance Methods
Calculates an attribute type
@private @since 0.5.0
# File lib/active_attr/typecasted_attributes.rb, line 66 def _attribute_type(attribute_name) self.class._attribute_type(attribute_name) end
Resolve an attribute typecaster
@private @since 0.6.0
# File lib/active_attr/typecasted_attributes.rb, line 74 def _attribute_typecaster(attribute_name) type = _attribute_type(attribute_name) self.class.attributes[attribute_name][:typecaster] || typecaster_for(type) or raise UnknownTypecasterError, "Unable to cast to type #{type}" end
Reads the attribute and typecasts the result
@since 0.5.0
ActiveAttr::Attributes#attribute
# File lib/active_attr/typecasted_attributes.rb, line 58 def attribute(name) typecast_attribute(_attribute_typecaster(name), super) end