Created
September 25, 2018 16:25
-
-
Save dan987/cbf73db11cdb2a5ee02722e076dabdb6 to your computer and use it in GitHub Desktop.
async audited with sidekiq (https://github.com/collectiveidea/audited) (https://jimmenard.com/2017/05/03/async-audits-are-awesome.html)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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