module CIA::Auditable::ClassMethods

Public Instance Methods

audit_attribute(*attributes) click to toggle source
# 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) click to toggle source
# 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