Class: ActiveData::Model::Associations::Base

Inherits:
Object
  • Object
show all
Defined in:
lib/active_data/model/associations/base.rb

Direct Known Subclasses

EmbedsAny, ReferencesAny

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(owner, reflection) ⇒ Base

Returns a new instance of Base.



8
9
10
11
12
13
# File 'lib/active_data/model/associations/base.rb', line 8

def initialize(owner, reflection)
  @owner = owner
  @reflection = reflection
  @evar_loaded = owner.persisted?
  reset
end

Instance Attribute Details

#ownerObject

Returns the value of attribute owner.



5
6
7
# File 'lib/active_data/model/associations/base.rb', line 5

def owner
  @owner
end

#reflectionObject

Returns the value of attribute reflection.



5
6
7
# File 'lib/active_data/model/associations/base.rb', line 5

def reflection
  @reflection
end

Instance Method Details

#apply_changes!Object



43
44
45
# File 'lib/active_data/model/associations/base.rb', line 43

def apply_changes!
  apply_changes or raise ActiveData::AssociationChangesNotApplied
end

#callback(name, object) ⇒ Object



47
48
49
50
51
52
53
54
55
56
57
58
59
60
# File 'lib/active_data/model/associations/base.rb', line 47

def callback(name, object)
  evaluator = reflection.options[name]
  return true unless evaluator

  if evaluator.is_a?(Proc)
    if evaluator.arity == 1
      owner.instance_exec(object, &evaluator)
    else
      evaluator.call(owner, object)
    end
  else
    owner.send(evaluator, object)
  end
end

#evar_loaded?Boolean

Returns:



20
21
22
# File 'lib/active_data/model/associations/base.rb', line 20

def evar_loaded?
  !!@evar_loaded
end

#inspectObject



71
72
73
# File 'lib/active_data/model/associations/base.rb', line 71

def inspect
  "#<#{reflection.macro.to_s.camelize} #{target.inspect.truncate(50, omission: collection? ? '...]' : '...')}>"
end

#loaded!Object



28
29
30
31
# File 'lib/active_data/model/associations/base.rb', line 28

def loaded!
  @evar_loaded = true
  @loaded = true
end

#loaded?Boolean

Returns:



24
25
26
# File 'lib/active_data/model/associations/base.rb', line 24

def loaded?
  !!@loaded
end

#reloadObject



38
39
40
41
# File 'lib/active_data/model/associations/base.rb', line 38

def reload
  reset
  target
end

#resetObject



15
16
17
18
# File 'lib/active_data/model/associations/base.rb', line 15

def reset
  @loaded = false
  @target = nil
end

#targetObject



33
34
35
36
# File 'lib/active_data/model/associations/base.rb', line 33

def target
  return @target if loaded?
  self.target = load_target
end

#transactionObject



62
63
64
65
66
67
68
69
# File 'lib/active_data/model/associations/base.rb', line 62

def transaction
  data = read_source.deep_dup
  yield
rescue StandardError => e
  write_source data
  reload
  raise e
end