Class: ActiveData::Model::Associations::ReferencesOne

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

Instance Attribute Summary

Attributes inherited from Base

#owner, #reflection

Instance Method Summary collapse

Methods inherited from Base

#apply_changes!, #evar_loaded?, #initialize, #inspect, #loaded!, #loaded?, #reload, #reset, #target, #transaction

Constructor Details

This class inherits a constructor from ActiveData::Model::Associations::Base

Instance Method Details

#apply_changesObject



5
6
7
8
9
10
11
12
# File 'lib/active_data/model/associations/references_one.rb', line 5

def apply_changes
  if target && !target.marked_for_destruction?
    write_source identify
  else
    write_source nil
  end
  true
end

#defaultObject



24
25
26
27
28
29
30
31
32
33
34
35
36
# File 'lib/active_data/model/associations/references_one.rb', line 24

def default
  unless evar_loaded?
    default = reflection.default(owner)
    case default
    when reflection.klass
      default
    when Hash
      reflection.klass.new(default)
    else
      scope(default).first
    end if default
  end
end

#identifyObject



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

def identify
  target.try(reflection.primary_key)
end

#load_targetObject



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

def load_target
  source = read_source
  source ? scope(source).first : default
end

#read_sourceObject



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

def read_source
  attribute.read_before_type_cast
end

#reader(force_reload = false) ⇒ Object



46
47
48
49
# File 'lib/active_data/model/associations/references_one.rb', line 46

def reader force_reload = false
  reset if force_reload
  target
end

#replace(object) ⇒ Object Also known as: writer



51
52
53
54
55
56
57
58
59
60
61
62
63
64
# File 'lib/active_data/model/associations/references_one.rb', line 51

def replace object
  unless object.nil? || object.is_a?(reflection.klass)
    raise AssociationTypeMismatch.new(reflection.klass, object.class)
  end

  transaction do
    attribute.pollute do
      self.target = object
      apply_changes!
    end
  end

  target
end

#scope(source = read_source) ⇒ Object



67
68
69
# File 'lib/active_data/model/associations/references_one.rb', line 67

def scope source = read_source
  reflection.scope.where(reflection.primary_key => source)
end

#target=(object) ⇒ Object



14
15
16
17
# File 'lib/active_data/model/associations/references_one.rb', line 14

def target= object
  loaded!
  @target = object
end

#write_source(value) ⇒ Object



42
43
44
# File 'lib/active_data/model/associations/references_one.rb', line 42

def write_source value
  attribute.write_value value
end