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

Defined in:
lib/wrest/components/container/typecaster.rb

Instance Method Summary collapse

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">


101
102
103
# File 'lib/wrest/components/container/typecaster.rb', line 101

def typecast(cast_map)
  @typecast_map = @typecast_map ? @typecast_map.merge(cast_map.symbolize_keys) : cast_map.symbolize_keys
end

#typecast_mapObject

:nodoc:



105
106
107
108
109
110
111
112
113
# File 'lib/wrest/components/container/typecaster.rb', line 105

def typecast_map #:nodoc:
  if defined?(@typecast_map)
    @typecast_map
  elsif superclass != Object && superclass.respond_to?(:typecast_map)
    superclass.typecast_map
  else
    {}
  end
end