Module: VirtualBox::AbstractModel::Relatable::ClassMethods

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

Instance Method Summary

Instance Method Details

- (Boolean) has_relationship?(name)

Returns a boolean of whether a relationship exists.

Returns:

  • (Boolean)


165
166
167
# File 'lib/virtualbox/abstract_model/relatable.rb', line 165

def has_relationship?(name)
  !!relationships.detect { |r| r[0] == name }
end

- (Object) inherited(subclass)

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



172
173
174
175
176
177
178
# File 'lib/virtualbox/abstract_model/relatable.rb', line 172

def inherited(subclass)
  super rescue NoMethodError

  relationships.each do |name, options|
    subclass.relationship(name, nil, options)
  end
end

- (Object) relationship(name, klass, options = {})

Define a relationship. The name and class must be specified. This class will be used to call the populate_relationship, save_relationship`, etc. methods.

Parameters:

  • (Symbol) name — Relationship name. This will also be used for the dynamically generated accessor.
  • (Class) klass — Class of the relationship.

Options Hash (options):

  • (Symbol) :dependent — default: nil


136
137
138
139
140
141
142
143
144
145
146
# File 'lib/virtualbox/abstract_model/relatable.rb', line 136

def relationship(name, klass, options = {})
  name = name.to_sym

  relationships << [name, { :klass => klass }.merge(options)]

  # Define the method to read the relationship
  define_method(name) { read_relationship(name) }

  # Define the method to set the relationship
  define_method("#{name}=") { |*args| set_relationship(name, *args) }
end

- (Array) relationships

Returns an array of the relationships in order of being added.

Returns:

  • (Array)


158
159
160
# File 'lib/virtualbox/abstract_model/relatable.rb', line 158

def relationships
  @relationships ||= []
end

- (Hash) relationships_hash

Returns a hash of all the relationships.

Returns:

  • (Hash)


151
152
153
# File 'lib/virtualbox/abstract_model/relatable.rb', line 151

def relationships_hash
  Hash[*relationships.flatten]
end