Module: VirtualBox::AbstractModel::Attributable::ClassMethods

Defined in:
lib/virtualbox/abstract_model/attributable.rb

Overview

Defines the class methods for the Attributable module. For detailed overview documentation, see Attributable.

Instance Method Summary

Instance Method Details

- (Object) attribute(name, options = {})

Defines an attribute on the model.

Parameters:

  • (Symbol) name — The name of the attribute, which will also be used to set the accessor methods.

Options Hash (options):

  • (Boolean) :readonly — default: false —If true, attribute will be readonly. More specifically, the attribute= method won't be defined for it.
  • (Object) :default — default: nil —Specifies a default value for the attribute.
  • (Symbol) :populate_key — default: attribute name —Specifies a custom populate key to use for Attributable#populate_attributes


138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
# File 'lib/virtualbox/abstract_model/attributable.rb', line 138

def attribute(name, options = {})
  name = name.to_sym
  attributes[name] = options

  # Create the method for reading this attribute
  define_method(name) { read_attribute(name) }

  # Create the writer method for it unless the attribute is readonly,
  # then remove the method if it exists
  if !options[:readonly]
    define_method("#{name}=") do |value|
      write_attribute(name, value)
    end
  elsif method_defined?("#{name}=")
    undef_method("#{name}=")
  end
end

- (Object) attributes

Returns the hash of attributes and their associated options.



157
158
159
# File 'lib/virtualbox/abstract_model/attributable.rb', line 157

def attributes
  @attributes ||= {}
end

- (Object) inherited(subclass)

Used to propagate attributes to subclasses. This method makes sure that subclasses of a class with Attributable included will inherit the attributes as well, which would be the expected behaviour.



164
165
166
167
168
169
170
# File 'lib/virtualbox/abstract_model/attributable.rb', line 164

def inherited(subclass)
  super rescue NoMethodError

  attributes.each do |name, option|
    subclass.attribute(name, option)
  end
end