Module: Wrest::Components::AttributesContainer

Included in:
Resource::Base
Defined in:
lib/wrest/components/attributes_container.rb,
lib/wrest/components/attributes_container.rb,
lib/wrest/components/attributes_container/typecaster.rb

Overview

Adds behaviour allowing a class to contain attributes and providing support for dynamic getters, setters and query methods. These methods are added at runtime, on the first invocation and on a per instance basis. respond_to? however will respond as though they are all already present. This means that two different instances of the same AttributesContainer could well have different attribute getters/setters/query methods.

Note that the first call to a particular getter/setter/query method will be slower because the method is defined at that point; subsequent calls will be much faster.

Also keep in mind that attribute getter/setter/query methods will not override any existing methods on the class.

In situations where this is a problem, such as a client consuming Rails REST services where id is a common attribute and clashes with Object#id, it is recommended to create getter/setter/query methods on the class (which affects all instances) using the always_has macro.

If you’re implementing your own initialize method remember to delegate to the default initialize of AttributesContainer by invoking super(attributes)

Example:

class ShenCoin
  include Wrest::Components::AttributesContainer
  include Wrest::Components::AttributesContainer::Typecaster

  always_has   :id
  typecast         :id   =>  as_integer
end
coin = ShenCoin.new(:id => '5', :chi_count => 500, :owner => 'Kai Wren')
coin.id    # => 5
coin.owner # => 'Kai Wren'

Defined Under Namespace

Modules: ClassMethods, InstanceMethods, Typecaster

Class Method Summary collapse

Class Method Details

.build_attribute_getter(attribute_name) ⇒ Object

:nodoc:



63
64
65
# File 'lib/wrest/components/attributes_container.rb', line 63

def self.build_attribute_getter(attribute_name) #:nodoc:
  "def #{attribute_name};@attributes[:#{attribute_name}];end;"
end

.build_attribute_queryer(attribute_name) ⇒ Object

:nodoc:



71
72
73
# File 'lib/wrest/components/attributes_container.rb', line 71

def self.build_attribute_queryer(attribute_name) #:nodoc:
  "def #{attribute_name}?;not @attributes[:#{attribute_name}].nil?;end;"
end

.build_attribute_setter(attribute_name) ⇒ Object

:nodoc:



67
68
69
# File 'lib/wrest/components/attributes_container.rb', line 67

def self.build_attribute_setter(attribute_name) #:nodoc:
  "def #{attribute_name}=(value);@attributes[:#{attribute_name}] = value;end;"
end

.included(klass) ⇒ Object

:nodoc:



58
59
60
61
# File 'lib/wrest/components/attributes_container.rb', line 58

def self.included(klass) #:nodoc:
  klass.extend AttributesContainer::ClassMethods
  klass.class_eval{ include AttributesContainer::InstanceMethods }
end