Class: PlainRecord::AssociationProxy

Inherits:
Array
  • Object
show all
Defined in:
lib/plain_record/association_proxy.rb

Overview

Storage for one-to-many virtual associations. When new object will pushed, proxy change it mapped fields.

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(array, owner, field) ⇒ AssociationProxy

Create proxy for one-to-many virtual associations field in owner with array in value.



41
42
43
44
45
# File 'lib/plain_record/association_proxy.rb', line 41

def initialize(array, owner, field)
  @owner = owner
  @field = field
  super(array)
end

Instance Attribute Details

#fieldObject

Associations field name.



29
30
31
# File 'lib/plain_record/association_proxy.rb', line 29

def field
  @field
end

#ownerObject

Model with association.



26
27
28
# File 'lib/plain_record/association_proxy.rb', line 26

def owner
  @owner
end

Class Method Details

Create proxy for one-to-many virtual associations field in owner and put array into it.



33
34
35
36
37
# File 'lib/plain_record/association_proxy.rb', line 33

def self.link(array, owner, field)
  proxy = new(array, owner, field)
  proxy.each { |i| proxy.link(i) }
  proxy
end

Instance Method Details

#<<(obj) ⇒ Object

Push new item in association and change it field by association map.



48
49
50
51
# File 'lib/plain_record/association_proxy.rb', line 48

def <<(obj)
  link(obj)
  super(obj)
end

Change fields in obj by association map.



54
55
56
57
58
# File 'lib/plain_record/association_proxy.rb', line 54

def link(obj)
  @owner.class.association_maps[@field].each do |from, to|
    obj.send(from.to_s + '=', @owner.send(to))
  end
end