Skip to content

Instantly share code, notes, and snippets.

@dougc84
Last active December 10, 2015 06:08
Show Gist options
  • Save dougc84/4392334 to your computer and use it in GitHub Desktop.
Save dougc84/4392334 to your computer and use it in GitHub Desktop.
Audited initializer to globally disable audits except when needed.
# Audited initializer to globally disable audits except when needed.
# https://gist.github.com/4392334
#
# Hacked from idea originally provided in issue:
# https://github.com/collectiveidea/audited/issues/18
# by Frost (github.com/Frost)
#
# Modified by Doug Clark (github.com/dougc84)
#
# Add this in an initializer (audited.rb)
#
# This will disable site-wide auditing if you only have a few use cases,
# such as only tracking audits for admins, or on specific types of
# activities. See comments under AuditedInstanceMethods for
# usage examples.
#
module Audited::InstanceMethods
private
def write_audit(attrs)
super if auditing_enabled && Audit.auditing_enabled?
end
end
class Audit
@@auditing_enabled = false
def self.auditing_enabled?
@@auditing_enabled
end
def self.disable_auditing
@@auditing_enabled = false
end
def self.enable_auditing
@@auditing_enabled = true
end
end
module Audited::Auditor
module AuditedInstanceMethods
# Executes a save action on a model with auditing enabled.
#
# object.something => "one"
# object.something = "two"
# object.save
# object.audits.count => 0
# object.something = "three"
# object.save_with_auditing
# object.audits.count => 1
#
def save_with_auditing
with_auditing { save }
end
# Executes a block with auditing enabled.
#
# SomeObject.with_auditing do
# object = SomeObject.first
# object.something => "one"
# object.audits.count => 0
# object.update_attributes(params[:some_object])
# end
# SomeObject.first.audits.count => 1
#
def with_auditing(&block)
self.class.with_auditing(&block)
end
end
module AuditedClassMethods
# Executes the block with auditing enabled.
#
# Foo.with_auditing do
# @foo.save
# end
#
def with_auditing(&block)
Audit.enable_auditing
yield
Audit.disable_auditing
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment