Class: DBViewCTI::Model::ModelDelegator

Inherits:
SimpleDelegator
  • Object
show all
Defined in:
lib/db_view_cti/model/model_delegator.rb

Defined Under Namespace

Modules: ForcePersistedState

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(object, target_class) ⇒ ModelDelegator

Returns a new instance of ModelDelegator.



10
11
12
13
14
15
16
17
18
19
20
# File 'lib/db_view_cti/model/model_delegator.rb', line 10

def initialize(object, target_class)
  @cti_object = object
  @cti_converted_object = object.convert_to(target_class)
  if !@cti_converted_object
    @cti_converted_object = target_class.constantize.new
    @cti_is_new = true
  end
  disable_validations
  @cti_target_class = target_class
  super( @cti_converted_object )
end

Instance Attribute Details

#cti_target_classObject (readonly)

Returns the value of attribute cti_target_class.



8
9
10
# File 'lib/db_view_cti/model/model_delegator.rb', line 8

def cti_target_class
  @cti_target_class
end

Instance Method Details

#cti_is_new?Boolean

Returns:

  • (Boolean)


22
23
24
# File 'lib/db_view_cti/model/model_delegator.rb', line 22

def cti_is_new?
  @cti_is_new
end

#save(*args, &block) ⇒ Object



26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
# File 'lib/db_view_cti/model/model_delegator.rb', line 26

def save(*args, &block)
  return super unless cti_is_new?
  # special case for new objects, we need to manually set the id and trick the object
  # to think it was already persisted, so we get an update instead of an insert
  new_id = @cti_object.convert_to( @cti_target_class ).id
  self.id = new_id
  force_persisted_state
  self.created_at = @cti_object.created_at
  self.updated_at = @cti_object.updated_at
  retval = !!super
  # throw away just saved object and convert from scratch
  @cti_converted_object = @cti_object.convert_to( @cti_target_class )
  disable_validations
  __setobj__(@cti_converted_object)
  return retval
end