module SoftLayer::DynamicAttribute::ClassMethods

Public Instance Methods

sl_dynamic_attr(attribute_name) { |attribute_definition| ... } click to toggle source

#sl_dynamic_attr declares a new dynamic softlayer attribute and accepts a block in which the should_update? and to_update methods for the attribute are established.

# File lib/softlayer/DynamicAttribute.rb, line 100
def sl_dynamic_attr (attribute_name, &block)
  attribute_definition = DynamicAttributeDefinition.new(attribute_name)

  # allow the block to update the attribute definition
  yield attribute_definition if block_given?

  # store off the attribute definition where we can find it later
  @attribute_definitions ||= {};
  @attribute_definitions[attribute_name] = attribute_definition;

  # define a method called "update_<attribute_name>!" which calls the update block
  # stored in the attribute definition
  update_symbol = "update_#{attribute_name}!".to_sym
  define_method(update_symbol, &attribute_definition.update_block)

  # define a method called "should_update_<attribute_name>?" which calls the
  # should update block stored in the attribute definition
  should_update_symbol = "should_update_#{attribute_name}?".to_sym
  define_method(should_update_symbol, &attribute_definition.should_update_block)

  # define an instance method of the class this is being
  # called on which will get the value of the attribute.
  #
  # The getter will take one argument "force_update" which
  # is treated as boolean value. If true, then the getter will
  # force the attribute to update (by using its "to_update") block.
  #
  # If the force variable is false, or not given, then the
  # getter will call the "should update" block to find out if the
  # attribute needs to be updated.
  #
  getter_name = attribute_name.to_sym
  value_instance_variable = "@#{attribute_name}".to_sym

  define_method(getter_name) do |*args|
    force_update = args[0] || false

    if force_update || __send__(should_update_symbol)
      instance_variable_set(value_instance_variable, __send__(update_symbol))
    end

    instance_variable_get(value_instance_variable)
  end
end
sl_dynamic_attr_definition(attribute_name) click to toggle source
# File lib/softlayer/DynamicAttribute.rb, line 145
def sl_dynamic_attr_definition(attribute_name)
  @attribute_definitions[attribute_name]
end