module SoftLayer::DynamicAttribute
This module is intended to be used by classes in the SoftLayer object model. It creates a small DSL for creating attributes that update themselves dynamically (usually by making requests to the SoftLayer API)
sl_dynamic_attr
is an implementation of a memoization scheme
The module creates a getter which is implemented in terms of a predicate
(identifying whether or not the attribute needs to be updated) and an
update routine
When the getter is called, it checks the predicate routine to see if the attribute needs to be updated. If it doesn't, then the getter simply returns the cached value for the attribute. If the attribute does need to be updated, the getter calls the update routine to get a new value and caches that value off before returning it to the caller.
Declaring a attribute adds three methods to a class and a corresponding instance variable in instances of the class All three are based on the name of the attribute:
-
The getter simply has the same name as the attribute
-
The predicate routine is called +should_update_<attribute name>?+
-
The updating routine is called +update_<attribute name>!+
The getter can also be called with a boolean argument. If that argument is
true, the getter will force the attribute to be updated without consulting
the should_update?
predicate
When a attribute is defined, the definition takes a block. Inside the block
there is a small DSL that allows you to set the behavior of the
should_update?
predicate and the update_!
routine.
A attribute definition might look something like this:
sl_dynamic_attr :lollipop do |lollipop| lollipop.should_update? do self.lollipop_supply_is_low? end lollipop.to_update do candy_store.buy_lollipops(bakers_dozen) end end
Public Class Methods
# File lib/softlayer/DynamicAttribute.rb, line 150 def self.included(included_in) included_in.extend(ClassMethods) end