Module: SoftLayer::DynamicAttribute::ClassMethods

Defined in:
lib/softlayer/DynamicAttribute.rb

Instance Method Summary collapse

Instance Method Details

#sl_dynamic_attr(attribute_name) {|attribute_definition| ... } ⇒ Object

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.

Yields:

  • (attribute_definition)


100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
# 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) ⇒ Object



145
146
147
# File 'lib/softlayer/DynamicAttribute.rb', line 145

def sl_dynamic_attr_definition(attribute_name)
  @attribute_definitions[attribute_name]
end