Module: Modelish::PropertyTypes::ClassMethods

Defined in:
lib/modelish/property_types.rb

Overview

Class methods for managing typed properties

Instance Method Summary collapse

Instance Method Details

#add_property_type(property_name, property_type = String) ⇒ Object

Adds a typed property to the model. This dynamically generates accessor/mutator methods that perform the appropriate type conversions on the property's value.

Generated methods:

  • +=(new_value)+ -- sets the property value.
  • ++ -- returns the property value, converted to the configured type. If the value cannot be converted, no error will be raised, and the raw unconverted value will be returned.
  • +!+ -- returns the property value, converted to the configured type. If the value cannot be converted, a TypeError will be raised.
  • +raw_ -- the original property value, without any type conversions.

    • +Integer+
    • +Float+
    • +Array+
    • +Date+ -- converts using Date.parse on value.to_s
    • +DateTime+ -- converts using DateTime.parse on value.to_s
    • +Symbol+ -- also converts from camel case to snake case
    • +String+
    • any arbitrary +Class+ -- will attempt conversion by passing the raw value into the class's initializer
    • an instance of +Proc+ -- will convert the value by executing the proc, passing in the raw value

Parameters:

  • property_name (Symbol)

    the name of the property.

  • property_type (Class, Proc) (defaults to: String)

    the type of the property's value. Valid types include:



44
45
46
47
48
49
50
51
52
53
54
55
56
57
# File 'lib/modelish/property_types.rb', line 44

def add_property_type(property_name, property_type = String)
  accessor = property_name.to_sym
  return if property_types[accessor] == property_type

  property_types[accessor] = property_type

  # Protected attributes used during type conversion
  define_raw_attribute(accessor)
  define_bang_attribute(accessor)
  define_typed_attribute(accessor)
  define_safe_attribute(accessor)

  define_public_attribute(accessor)
end

#property_typesObject



59
60
61
# File 'lib/modelish/property_types.rb', line 59

def property_types
  @property_types ||= {}
end