Class: DuckRecord::Associations::EmbedsAssociation

Inherits:
Object
  • Object
show all
Defined in:
lib/duck_record/associations/embeds_association.rb

Overview

Active Record Associations

This is the root class of all associations (‘+ Foo’ signifies an included module Foo):

Association
  SingularAssociation
    HasOneAssociation + ForeignAssociation
      HasOneThroughAssociation + ThroughAssociation
    BelongsToAssociation
      BelongsToPolymorphicAssociation
  CollectionAssociation
    HasManyAssociation + ForeignAssociation
      HasManyThroughAssociation + ThroughAssociation

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(owner, reflection) ⇒ EmbedsAssociation

Returns a new instance of EmbedsAssociation.



23
24
25
26
27
28
29
# File 'lib/duck_record/associations/embeds_association.rb', line 23

def initialize(owner, reflection)
  reflection.check_validity!

  @owner, @reflection = owner, reflection

  reset
end

Instance Attribute Details

#ownerObject (readonly)

:nodoc:



19
20
21
# File 'lib/duck_record/associations/embeds_association.rb', line 19

def owner
  @owner
end

#reflectionObject (readonly)

:nodoc:



19
20
21
# File 'lib/duck_record/associations/embeds_association.rb', line 19

def reflection
  @reflection
end

#targetObject

:nodoc:



19
20
21
# File 'lib/duck_record/associations/embeds_association.rb', line 19

def target
  @target
end

Instance Method Details

#initialize_attributes(record, attributes = nil) ⇒ Object

:nodoc:



64
65
66
67
# File 'lib/duck_record/associations/embeds_association.rb', line 64

def initialize_attributes(record, attributes = nil) #:nodoc:
  attributes ||= {}
  record.assign_attributes(attributes)
end

#klassObject

Returns the class of the target. belongs_to polymorphic overrides this to look at the polymorphic_type field on the owner.



48
49
50
# File 'lib/duck_record/associations/embeds_association.rb', line 48

def klass
  reflection.klass
end

#loaded?Boolean

Has the target been already loaded?

Returns:

  • (Boolean)


37
38
39
# File 'lib/duck_record/associations/embeds_association.rb', line 37

def loaded?
  !!@target
end

#marshal_dumpObject

We can’t dump @reflection since it contains the scope proc



53
54
55
56
# File 'lib/duck_record/associations/embeds_association.rb', line 53

def marshal_dump
  ivars = (instance_variables - [:@reflection]).map { |name| [name, instance_variable_get(name)] }
  [@reflection.name, ivars]
end

#marshal_load(data) ⇒ Object



58
59
60
61
62
# File 'lib/duck_record/associations/embeds_association.rb', line 58

def marshal_load(data)
  reflection_name, ivars = data
  ivars.each { |name, val| instance_variable_set(name, val) }
  @reflection = @owner.class._reflect_on_association(reflection_name)
end

#resetObject

Resets the loaded flag to false and sets the target to nil.



32
33
34
# File 'lib/duck_record/associations/embeds_association.rb', line 32

def reset
  @target = nil
end