Class: Granite::Form::Model::Associations::Base

Inherits:
Object
  • Object
show all
Defined in:
lib/granite/form/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.



10
11
12
13
14
15
# File 'lib/granite/form/model/associations/base.rb', line 10

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

Instance Attribute Details

#ownerObject

Returns the value of attribute owner.



6
7
8
# File 'lib/granite/form/model/associations/base.rb', line 6

def owner
  @owner
end

#reflectionObject

Returns the value of attribute reflection.



6
7
8
# File 'lib/granite/form/model/associations/base.rb', line 6

def reflection
  @reflection
end

Instance Method Details

#callback(name, object) ⇒ Object



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

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:



22
23
24
# File 'lib/granite/form/model/associations/base.rb', line 22

def evar_loaded?
  !!@evar_loaded
end

#inspectObject



70
71
72
73
74
# File 'lib/granite/form/model/associations/base.rb', line 70

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

#loaded!Object



30
31
32
33
# File 'lib/granite/form/model/associations/base.rb', line 30

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

#loaded?Boolean

Returns:



26
27
28
# File 'lib/granite/form/model/associations/base.rb', line 26

def loaded?
  !!@loaded
end

#reloadObject



41
42
43
44
# File 'lib/granite/form/model/associations/base.rb', line 41

def reload
  reset
  target
end

#resetObject



17
18
19
20
# File 'lib/granite/form/model/associations/base.rb', line 17

def reset
  @loaded = false
  @target = nil
end

#targetObject



35
36
37
38
39
# File 'lib/granite/form/model/associations/base.rb', line 35

def target
  return @target if loaded?

  self.target = load_target
end

#transactionObject



61
62
63
64
65
66
67
68
# File 'lib/granite/form/model/associations/base.rb', line 61

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