Class: Humanoid::Associations::HasOneRelated

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

Overview

:nodoc:

Class Method Summary collapse

Instance Method Summary collapse

Methods included from Proxy

included

Constructor Details

#initialize(document, options, target = nil) ⇒ HasOneRelated

Initializing a related association only requires looking up the objects by their ids.

Options:

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



34
35
36
37
38
39
# File 'lib/humanoid/associations/has_one_related.rb', line 34

def initialize(document, options, target = nil)
  @parent, @klass = document, options.klass
  @foreign_key = document.class.to_s.foreign_key
  @target = target || @klass.first(:conditions => { @foreign_key => @parent.id })
  extends(options)
end

Class Method Details

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

Preferred method for creating the new RelatesToMany association.

Options:

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



48
49
50
# File 'lib/humanoid/associations/has_one_related.rb', line 48

def instantiate(document, options, target = nil)
  new(document, options, target)
end

.macroObject

Returns the macro used to create the association.



53
54
55
# File 'lib/humanoid/associations/has_one_related.rb', line 53

def macro
  :has_one_related
end

.update(target, document, 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 to update. document: The parent Document. options: The association Options

Example:

HasOneToRelated.update(game, person, options)



69
70
71
72
73
74
75
76
# File 'lib/humanoid/associations/has_one_related.rb', line 69

def update(target, document, options)
  if target
    name = document.class.to_s.underscore
    target.send("#{name}=", document)
    return instantiate(document, options, target)
  end
  target
end

Instance Method Details

#build(attributes = {}) ⇒ Object

Builds a new Document and sets it as the association.

Returns the newly created object.



12
13
14
15
16
17
# File 'lib/humanoid/associations/has_one_related.rb', line 12

def build(attributes = {})
  @target = @klass.instantiate(attributes)
  name = @parent.class.to_s.underscore
  @target.send("#{name}=", @parent)
  @target
end

#create(attributes) ⇒ Object

Builds a new Document and sets it as the association, then saves the newly created document.

Returns the newly created object.



23
24
25
# File 'lib/humanoid/associations/has_one_related.rb', line 23

def create(attributes)
  build(attributes); @target.save; @target
end