Class: EntitySchema::Fields::ObserverBelongsTo

Inherits:
Object
  • Object
show all
Defined in:
lib/entity_schema/fields/observer_belongs_to.rb

Overview

Doc

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(fk_belongs_to, object_belongs_to, object_pk:) ⇒ ObserverBelongsTo

Returns a new instance of ObserverBelongsTo.



9
10
11
12
13
# File 'lib/entity_schema/fields/observer_belongs_to.rb', line 9

def initialize(fk_belongs_to, object_belongs_to, object_pk:)
  @fk_field     = fk_belongs_to
  @object_field = object_belongs_to
  @object_pk    = object_pk
end

Instance Attribute Details

#fk_fieldObject (readonly)

Returns the value of attribute fk_field.



7
8
9
# File 'lib/entity_schema/fields/observer_belongs_to.rb', line 7

def fk_field
  @fk_field
end

#object_fieldObject (readonly)

Returns the value of attribute object_field.



7
8
9
# File 'lib/entity_schema/fields/observer_belongs_to.rb', line 7

def object_field
  @object_field
end

#object_pkObject (readonly)

Returns the value of attribute object_pk.



7
8
9
# File 'lib/entity_schema/fields/observer_belongs_to.rb', line 7

def object_pk
  @object_pk
end

Instance Method Details

#fk_changed(new_fk, obj) ⇒ Object



15
16
17
18
19
20
# File 'lib/entity_schema/fields/observer_belongs_to.rb', line 15

def fk_changed(new_fk, obj)
  object = object_field.get(obj)
  return if object.nil?
  old_fk = object.public_send(object_pk)
  object_field.set(obj, nil) if new_fk != old_fk
end

#object_changed(new_object, obj) ⇒ Object



22
23
24
25
26
27
28
29
30
# File 'lib/entity_schema/fields/observer_belongs_to.rb', line 22

def object_changed(new_object, obj)
  new_pk =
    case new_object
    when Hash then new_object[object_pk]
    when nil  then nil
    else           new_object.public_send(object_pk)
    end
  fk_field.set(obj, new_pk, notify_observer: false)
end