Module: Modelish::PropertyTypes::ClassMethods
- Defined in:
- lib/modelish/property_types.rb
Instance Method Summary collapse
-
#add_property_type(property_name, property_type = String) ⇒ Object
Adds a typed property to the model.
- #property_types ⇒ Object
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: * +
Maruku could not parse this XML/HTML:
<property_name>=(new_value)+ -- sets the property value.
* +<property_name>+ -- 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.
* +<property_name>!+ -- returns the property value, converted to the configured
type. If the value cannot be converted, a TypeError will
be raised.
* +raw_<property_name> -- 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 as an argument
39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 |
# File 'lib/modelish/property_types.rb', line 39 def add_property_type(property_name, property_type=String) accessor = property_name.to_sym # TODO: Refactor. This method is getting unwieldy as more # corner cases are discovered. A few well-placed design # refinements should take care of it (now we just need to figure # out what those are.) unless property_types[accessor] == property_type property_types[accessor] = property_type raw_accessor = define_raw_accessor(accessor) bang_accessor = define_bang_accessor(accessor) typed_accessor = "_typed_#{accessor}".to_sym typed_mutator = "#{typed_accessor}=".to_sym to_safe = "_to_safe_#{accessor}".to_sym class_eval do attr_accessor typed_accessor private typed_accessor, typed_mutator define_method(to_safe) do self.send(bang_accessor) rescue self.send(raw_accessor) end private to_safe define_method(accessor) do val = self.send(typed_accessor) unless val || self.send(raw_accessor).nil? val = self.send(to_safe) self.send(typed_mutator, val) end val end define_method("#{accessor}=") do |val| self.send("#{raw_accessor}=", val) self.send(typed_mutator, self.send(to_safe)) end end end end |
#property_types ⇒ Object
84 85 86 |
# File 'lib/modelish/property_types.rb', line 84 def property_types @property_types ||= {} end |