Module: Scrivener::Types
- Included in:
- Scrivener
- Defined in:
- lib/scrivener/types.rb
Overview
Provides a way to define attributes so they are cast into a corresponding type (defaults to String
) when getting the attributes.
Any object that supports a .call method can be used as a “type”. The following are implemented out of the box:
-
Types::Symbol
-
Types::String
-
Types::Integer
-
Types::Float
-
Types::Decimal
-
Types::Date
-
Types::Time
-
Types::DateTime
-
Types::Boolean
Constant Summary collapse
- Symbol =
->(value) { value.to_sym }
- String =
->(value) { value.to_s }
- Integer =
->(value) { Integer(value) }
- Float =
->(value) { Float(value) }
- Decimal =
->(value) { BigDecimal(value) }
- Date =
->(value) { ::Date.parse(value.to_s) }
- DateTime =
->(value) { ::DateTime.parse(value.to_s) }
- Time =
->(value) { ::Time.parse(value.to_s) }
- Boolean =
->(value) { case value when "f", "false", "0"; false when "t", "true", "1"; true else !!value end }
Instance Method Summary collapse
-
#attribute(name, type = Types::String) ⇒ type
Define an attribute with its corresponding type.
Instance Method Details
#attribute(name, type = Types::String) ⇒ type
Define an attribute with its corresponding type. This is similar to attr_accessor, except the reader method will cast the object into the proper type.
If the casting results in a TypeError or ArgumentError, then an error on :typecast will be added to this attribute and the raw attribute will be returned instead.
73 74 75 76 77 78 79 80 81 82 83 84 85 |
# File 'lib/scrivener/types.rb', line 73 def attribute(name, type=Types::String) attr_writer name define_method name do begin val = instance_variable_get(:"@#{name}") val && type.call(val) rescue TypeError, ArgumentError errors[name].push(:typecast) val end end end |