Module: Wrest::Components::AttributesContainer::ClassMethods

Defined in:
lib/wrest/components/attributes_container.rb

Instance Method Summary collapse

Instance Method Details

#has_attributes(*attribute_names) ⇒ Object

This macro explicitly creates getter, setter and query methods on a class, overriding any exisiting methods with the same names. This can be used when attribute names clash with method names; an example would be Rails REST services which frequently make use an attribute named id which clashes with Object#id. Also, this can be used as a performance optimisation if the incoming attributes are known beforehand.



76
77
78
79
80
81
82
83
84
# File 'lib/wrest/components/attributes_container.rb', line 76

def has_attributes(*attribute_names)
  attribute_names.each do |attribute_name|
    self.class_eval(
      AttributesContainer.build_attribute_getter(attribute_name) +
      AttributesContainer.build_attribute_setter(attribute_name) +
      AttributesContainer.build_attribute_queryer(attribute_name)
    ) 
  end
end

#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 AttributesContainer directly from request params. Typecasting kicks in for a given value only if it is a string.

Typcast 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.

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


111
112
113
# File 'lib/wrest/components/attributes_container.rb', line 111

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

#typecast_mapObject

:nodoc:



115
116
117
118
119
120
121
122
123
# File 'lib/wrest/components/attributes_container.rb', line 115

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