module ActiveGraph::Shared::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 ActiveGraph::Shared::TypecastedAttributes
  attribute :age, :type => Integer
end

person = Person.new
person.age = "29"
person.age #=> 29
person.age_before_type_cast #=> "29"

Originally part of ActiveAttr, github.com/cgriego/active_attr

Public Instance Methods

attribute_before_type_cast(name) click to toggle source

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

   # File lib/active_graph/shared/typecasted_attributes.rb
41 def attribute_before_type_cast(name)
42   @attributes ||= ActiveGraph::AttributeSet.new({}, self.class.attributes.keys)
43   @attributes.fetch_value(name.to_s)
44 end

Private Instance Methods

_attribute_type(attribute_name) click to toggle source

Calculates an attribute type

@private

   # File lib/active_graph/shared/typecasted_attributes.rb
60 def _attribute_type(attribute_name)
61   self.class._attribute_type(attribute_name)
62 end
_attribute_typecaster(attribute_name) click to toggle source

Resolve an attribute typecaster

@private

   # File lib/active_graph/shared/typecasted_attributes.rb
67 def _attribute_typecaster(attribute_name)
68   type = _attribute_type(attribute_name)
69   default_typecaster = self.class.attributes[attribute_name].typecaster
70   caster = default_typecaster || ActiveGraph::Shared::TypeConverters.typecaster_for(type)
71   caster || fail(ActiveGraph::UnknownTypeConverterError, "Unable to cast to type #{type}")
72 end
attribute(name) click to toggle source

Reads the attribute and typecasts the result

   # File lib/active_graph/shared/typecasted_attributes.rb
49 def attribute(name)
50   Property::NEO4J_DRIVER_DATA_TYPES.include?(_attribute_type(name)) ? super : typecast_attribute(_attribute_typecaster(name), super)
51 end
typecast_attribute(typecaster, value) click to toggle source
   # File lib/active_graph/shared/typecasted_attributes.rb
53 def typecast_attribute(typecaster, value)
54   self.class.typecast_attribute(typecaster, value)
55 end