Module: Wrest::Components::AttributesContainer

Included in:
Resource::Base
Defined in:
lib/wrest/components/attributes_container.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 has_attributes 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

has_attributes  :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

Class Method Summary collapse

Class Method Details

.build_attribute_getter(attribute_name) ⇒ Object

:nodoc:



56
57
58
# File 'lib/wrest/components/attributes_container.rb', line 56

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

.build_attribute_queryer(attribute_name) ⇒ Object

:nodoc:



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

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:



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

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

.included(klass) ⇒ Object

:nodoc:



50
51
52
53
54
# File 'lib/wrest/components/attributes_container.rb', line 50

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