Skip to content

Instantly share code, notes, and snippets.

@dan987
Created September 25, 2018 16:25
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dan987/cbf73db11cdb2a5ee02722e076dabdb6 to your computer and use it in GitHub Desktop.
Save dan987/cbf73db11cdb2a5ee02722e076dabdb6 to your computer and use it in GitHub Desktop.
module Audited
class Audit
alias_method :after_save, :save
# NOTE: Hack fix checking for changes, still not sure why its triggering 2x
def save(*_args)
unless self.auditable.changed? # better way to get this not to fire 2x?
self.created_at ||= Time.current
conrtl = Audited.store[:current_controller]
if conrtl
self.user_id ||= conrtl.current_user&.id
self.user_type ||= conrtl.current_user&.class&.name
self.request_uuid ||= conrtl.request&.uuid
self.remote_address ||= conrtl.request&.remote_ip
end
self.username ||= self.user&.email
# Need to hack datetime values so they're encoded properly
attrs = attributes
attrs["created_at"] = attrs["created_at"].to_s(:db)
# Resque.enqueue(AuditingJob::AsyncSave, attrs)
Auditer.perform_async(attrs)
true
end
end
end
end
# Asycronous audits for postgres models
class Auditer
include Sidekiq::Worker
def perform(audit_attributes)
Audited::Audit.transaction do
audit_attributes['version'] = get_version(audit_attributes['auditable_id'],
audit_attributes['auditable_type'])
column_names = audit_attributes.keys.reject! { |k| k == 'id' }
@conn = Audited::Audit.connection
safe_values = safe_value(audit_attributes).drop(1)
@conn.execute "INSERT INTO #{Audited::Audit.table_name} (#{column_names.join(", ")})" +
" VALUES (#{safe_values.join(", ")})"
end
end
private
def get_version(auditable_id, auditable_type)
return 1 unless auditable_id && auditable_type
curr_version = Audited::Audit.where(auditable_id: auditable_id,
auditable_type: auditable_type)
.maximum(:version)
(curr_version || 0) + 1
end
def safe_value(audit_attributes)
audit_attributes.values.map do |v|
if v.class == Hash
@conn.quote(v.to_s)
else
@conn.quote(v)
end
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment