Module: CIA::Auditable::ClassMethods

Defined in:
lib/cia/auditable.rb

Instance Method Summary collapse

Instance Method Details

#audit_attribute(*attributes) ⇒ Object



30
31
32
33
34
35
36
37
38
39
40
41
# File 'lib/cia/auditable.rb', line 30

def audit_attribute(*attributes)
  options = (attributes.last.is_a?(Hash) ? attributes.pop : {})
  setup_auditing_callbacks(options)

  self.audited_attributes = attributes.map(&:to_s)

  raise "cannot have :if and :unless" if options[:if] && options[:unless]
  self.audited_attribute_options = options

  has_many :cia_events, class_name: "CIA::Event", as: :source
  has_many :cia_attribute_changes, class_name: "CIA::AttributeChange", as: :source
end

#setup_auditing_callbacks(options) ⇒ Object



43
44
45
46
47
48
49
50
51
52
53
54
55
56
# File 'lib/cia/auditable.rb', line 43

def setup_auditing_callbacks(options)
  return if audited_attributes_callbacks_added
  self.audited_attributes_callbacks_added = true

  [:create, :update, :destroy].each do |callback|
    method, args = if options[:callback] == :after_commit
      send("after_#{callback}"){ |record| record.cia_previous_changes(record.cia_changes) }
      [:after_commit, [{on: callback}]]
    else
      ["after_#{callback}", []]
    end
    send(method, *args) { |record| CIA.record(callback, record) }
  end
end