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

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

Instance Method Summary collapse

Instance Method Details

#has_relationship?(name) ⇒ Boolean

Returns a boolean of whether a relationship exists.

Returns:

  • (Boolean)


169
170
171
# File 'lib/virtualbox/abstract_model/relatable.rb', line 169

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

#inherited(subclass) ⇒ Object

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



176
177
178
179
180
181
182
# File 'lib/virtualbox/abstract_model/relatable.rb', line 176

def inherited(subclass)
  super rescue NoMethodError

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

#relationship(name, klass, options = {}) ⇒ Object

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:

  • name (Symbol)

    Relationship name. This will also be used for the dynamically generated accessor.

  • klass (Class)

    Class of the relationship.

  • options (Hash) (defaults to: {})

    a customizable set of options

Options Hash (options):



140
141
142
143
144
145
146
147
148
149
150
# File 'lib/virtualbox/abstract_model/relatable.rb', line 140

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

#relationshipsArray

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

Returns:

  • (Array)


162
163
164
# File 'lib/virtualbox/abstract_model/relatable.rb', line 162

def relationships
  @relationships ||= []
end

#relationships_hashHash

Returns a hash of all the relationships.

Returns:

  • (Hash)


155
156
157
# File 'lib/virtualbox/abstract_model/relatable.rb', line 155

def relationships_hash
  Hash[*relationships.flatten]
end