Module: Effective::Resources::Instance

Included in:
Effective::Resource
Defined in:
app/models/effective/resources/instance.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Instance Attribute Details

#instanceObject (readonly)

This is written for use by effective_logging and effective_trash



8
9
10
# File 'app/models/effective/resources/instance.rb', line 8

def instance
  @instance
end

Instance Method Details

#instance_attributesObject



12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
# File 'app/models/effective/resources/instance.rb', line 12

def instance_attributes
  return {} unless instance.present?

  attributes = { attributes: instance.attributes }

  # Collect to_s representations of all belongs_to associations
  belong_tos.each do |association|
    attributes[association.name] = instance.send(association.name).to_s
  end

  nested_resources.each do |association|
    attributes[association.name] ||= {}

    Array(instance.send(association.name)).each_with_index do |child, index|
      resource = Effective::Resource.new(child)
      attributes[association.name][index] = resource.instance_attributes
    end
  end

  has_ones.each do |association|
    attributes[association.name] = instance.send(association.name).to_s
  end

  has_manys.each do |association|
    attributes[association.name] = instance.send(association.name).map { |obj| obj.to_s }
  end

  has_and_belongs_to_manys.each do |association|
    attributes[association.name] = instance.send(association.name).map { |obj| obj.to_s }
  end

  attributes.delete_if { |_, value| value.blank? }
end

#instance_changesObject



46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
# File 'app/models/effective/resources/instance.rb', line 46

def instance_changes
  return {} unless (instance.present? && instance.changes.present?)

  changes = instance.changes.delete_if do |attribute, (before, after)|
    (before.kind_of?(ActiveSupport::TimeWithZone) && after.kind_of?(ActiveSupport::TimeWithZone) && before.to_i == after.to_i)
  end

  # Log to_s changes on all belongs_to associations
  belong_tos.each do |association|
    if (change = changes.delete(association.foreign_key)).present?
      changes[association.name] = [(association.klass.find_by_id(change.first) if changes.first), instance.send(association.name)]
    end
  end

  changes
end