Module Wrest::Components::Container::Typecaster::ClassMethods

  1. lib/wrest/components/container/typecaster.rb

Methods

public instance

  1. typecast

Public instance methods

typecast (cast_map)

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">
[show source]
     # File lib/wrest/components/container/typecaster.rb, line 101
101:         def typecast(cast_map)
102:           @typecast_map = @typecast_map ? @typecast_map.merge(cast_map.symbolize_keys) : cast_map.symbolize_keys
103:         end