Class: ActiveData::Model::Attributes::ReferenceOne

Inherits:
Base
  • Object
show all
Defined in:
lib/active_data/model/attributes/reference_one.rb

Direct Known Subclasses

ReferenceMany

Instance Attribute Summary

Attributes inherited from Base

#name, #owner

Instance Method Summary collapse

Methods inherited from Base

#came_from_default?, #came_from_user?, #initialize, #inspect_attribute, #pollute, #query, #readonly?, #reflection, #reset, #typecast, #value_present?, #write_value

Constructor Details

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

Instance Method Details

#readObject



16
17
18
19
20
21
22
# File 'lib/active_data/model/attributes/reference_one.rb', line 16

def read
  if association.target
    association.identify
  else
    type_casted_value
  end
end

#read_before_type_castObject



30
31
32
# File 'lib/active_data/model/attributes/reference_one.rb', line 30

def read_before_type_cast
  @value_cache
end

#typeObject



34
35
36
# File 'lib/active_data/model/attributes/reference_one.rb', line 34

def type
  @type ||= association.reflection.persistence_adapter.primary_key_type
end

#type_casted_valueObject



24
25
26
27
28
# File 'lib/active_data/model/attributes/reference_one.rb', line 24

def type_casted_value
  variable_cache(:value) do
    typecast(read_before_type_cast)
  end
end

#typecasterObject



38
39
40
# File 'lib/active_data/model/attributes/reference_one.rb', line 38

def typecaster
  @typecaster ||= ActiveData.typecaster(type.ancestors.grep(Class))
end

#write(value) ⇒ Object



5
6
7
8
9
10
11
12
13
14
# File 'lib/active_data/model/attributes/reference_one.rb', line 5

def write(value)
  pollute do
    previous = type_casted_value
    result = write_value value
    changed = (!value.nil? && type_casted_value.nil?) || type_casted_value != previous

    association.reset if changed
    result
  end
end