Class: Humanoid::Associations::BelongsToRelated

Inherits:
Object
  • Object
show all
Includes:
Proxy
Defined in:
lib/humanoid/associations/belongs_to_related.rb

Overview

:nodoc:

Class Method Summary collapse

Instance Method Summary collapse

Methods included from Proxy

included

Constructor Details

#initialize(document, foreign_key, options, target = nil) ⇒ BelongsToRelated

Initializing a related association only requires looking up the object by its id.

Options:

document: The Document that contains the relationship. options: The association Options.



14
15
16
17
18
# File 'lib/humanoid/associations/belongs_to_related.rb', line 14

def initialize(document, foreign_key, options, target = nil)
  @options = options
  @target = target || options.klass.find(foreign_key)
  extends(options)
end

Class Method Details

.instantiate(document, options, target = nil) ⇒ Object

Instantiate a new BelongsToRelated or return nil if the foreign key is nil. It is preferrable to use this method over the traditional call to new.

Options:

document: The Document that contains the relationship. options: The association Options.



29
30
31
32
# File 'lib/humanoid/associations/belongs_to_related.rb', line 29

def instantiate(document, options, target = nil)
  foreign_key = document.send(options.foreign_key)
  foreign_key.blank? ? nil : new(document, foreign_key, options, target)
end

.macroObject

Returns the macro used to create the association.



35
36
37
# File 'lib/humanoid/associations/belongs_to_related.rb', line 35

def macro
  :belongs_to_related
end

.update(target, parent, options) ⇒ Object

Perform an update of the relationship of the parent and child. This will assimilate the child Document into the parent’s object graph.

Options:

related: The related object parent: The parent Document to update. options: The association Options

Example:

BelongsToRelated.update(game, person, options)



51
52
53
54
55
56
57
# File 'lib/humanoid/associations/belongs_to_related.rb', line 51

def update(target, parent, options)
  if target
    parent.send("#{options.foreign_key}=", target.id)
    return instantiate(parent, options, target)
  end
  target
end