Module: Wrest::Components::Container::Typecaster::ClassMethods
- Defined in:
- lib/wrest/components/container/typecaster.rb
Instance Method Summary collapse
-
#typecast(cast_map) ⇒ Object
Accepts a set of attribute-name/lambda pairs which are used to typecast string values injected through the constructor.
-
#typecast_map ⇒ Object
:nodoc:.
Instance Method Details
#typecast(cast_map) ⇒ Object
Accepts a set of attribute-name/lambda pairs which are used
to typecast string values injected through the constructor.
Typically needed when populating an Container
directly from request params. Typecasting kicks in for
a given value only if it is a String, Hash or Array, the
three classes that deserilisation can produce.
Typecast information is inherited by subclasses; however be
aware that explicitly invoking typecast in a subclass will
discard inherited typecast information leaving only the casts
defined in the subclass.
Note that this will increase the time needed to initialize instances.
Common typecasts such as integer, float, datetime etc. are available through predefined helpers. See TypecastHelpers for a full list.
Example:
class Demon include Wrest::Components::Container include Wrest::Components::Container::Typecaster
typecast :age => as_integer,
:chi => lambda{|chi| Chi.new(chi)}
end
kai_wren = Demon.new('age' => '1500', 'chi' => '1024') kai_wren.age # => 1500 kai_wren.chi # => #<Chi:0x113af8c @count="1024">
147 148 149 |
# File 'lib/wrest/components/container/typecaster.rb', line 147 def typecast(cast_map) @typecast_map = @typecast_map ? @typecast_map.merge(cast_map.transform_keys(&:to_sym)) : cast_map.transform_keys(&:to_sym) end |
#typecast_map ⇒ Object
:nodoc:
151 152 153 154 155 156 157 158 159 |
# File 'lib/wrest/components/container/typecaster.rb', line 151 def typecast_map # :nodoc: if defined?(@typecast_map) @typecast_map elsif superclass != Object && superclass.respond_to?(:typecast_map) superclass.typecast_map else {} end end |