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_attributes(include_associated: true) ⇒ Object

called by effective_trash as defaults, and effective_logging sometimes with true or false



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
45
46
47
# File 'app/models/effective/resources/instance.rb', line 13

def instance_attributes(include_associated: true)
  return {} unless instance.present?

  attributes = { attributes: instance.attributes }

  # Collect to_s representations of all belongs_to associations
  if include_associated
    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
  end

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

#instance_changesObject

used by effective_logging



50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
# File 'app/models/effective/resources/instance.rb', line 50

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

  changes = instance.changes.delete_if do |attribute, (before, after)|
    begin
      (before.kind_of?(ActiveSupport::TimeWithZone) && after.kind_of?(ActiveSupport::TimeWithZone) && before.to_i == after.to_i) ||
      (before == nil && after == false) || (before == nil && after == ''.freeze)
    rescue => e
      true
    end
  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