Class: Changed::Audit

Inherits:
ApplicationRecord show all
Defined in:
app/models/changed/audit.rb

Defined Under Namespace

Modules: Event

Constant Summary collapse

EVENTS =
[
  Event::CREATE,
  Event::UPDATE,
].freeze

Instance Method Summary collapse

Instance Method Details

#anything?Boolean

Returns:

  • (Boolean)


60
61
62
# File 'app/models/changed/audit.rb', line 60

def anything?
  changeset.any? || associations.any?
end

#changed?(key) ⇒ Boolean

Returns:

  • (Boolean)


64
65
66
# File 'app/models/changed/audit.rb', line 64

def changed?(key)
  fields.map(&:name).include?(key)
end

#fieldsObject



29
30
31
32
33
34
# File 'app/models/changed/audit.rb', line 29

def fields
  changeset.map do |name, value|
    was, now = value
    Field.new(was, now, transform(name))
  end
end

#relationshipsObject



36
37
38
39
40
41
42
43
44
45
# File 'app/models/changed/audit.rb', line 36

def relationships
  memo = {}
  associations.each do |association|
    memo[association.name] ||= Set.new
    memo[association.name] << association
  end
  memo.map do |name, associations|
    Relationship.new(associations, transform(name))
  end
end

#track(event, fields) ⇒ Object



47
48
49
50
51
52
53
54
55
56
57
58
# File 'app/models/changed/audit.rb', line 47

def track(event, fields)
  self.changer = Changed.changer

  fields.each do |attribute|
    attribute = String(attribute)
    if audited.saved_change_to_attribute?(attribute)
      changeset[attribute] = audited.saved_change_to_attribute(attribute)
    end
  end

  self.event = event
end

#track_association_change(name, change) ⇒ Object



83
84
85
86
87
88
89
90
91
92
93
94
95
# File 'app/models/changed/audit.rb', line 83

def track_association_change(name, change)
  association_was = yield
  change.call
  association_now = yield
  return if association_was == association_now

  (association_was - association_now).each do |associated|
    associations.build(name: name, associated: associated, kind: :remove)
  end
  (association_now - association_was).each do |associated|
    associations.build(name: name, associated: associated, kind: :add)
  end
end

#track_attribute_change(attribute, change) ⇒ Object

The ‘change’ provided needs to be a block, lambda, or proc that executes the changes. The other provided block is yielded pre and post the change.



70
71
72
73
74
75
76
77
78
79
80
81
# File 'app/models/changed/audit.rb', line 70

def track_attribute_change(attribute, change)
  attribute_was = yield
  change.call
  attribute_now = yield

  return if attribute_was == attribute_now

  changeset[String(attribute)] = [
    attribute_was,
    attribute_now,
  ]
end