-
-
Save unixsuperhero/5167028 to your computer and use it in GitHub Desktop.
This file contains 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
commit 9d4f4c2b3bd0207bf9a02a4403b3f54cb5bf3ae4 | |
Author: Joshua Toyota <[email protected]> | |
Date: Wed Dec 19 11:29:58 2012 -0500 | |
autoaudit, with user as an example | |
diff --git a/app/models/user.rb b/app/models/user.rb | |
index 0077df0..f29e5d8 100644 | |
--- a/app/models/user.rb | |
+++ b/app/models/user.rb | |
@@ -1,7 +1,8 @@ | |
- | |
class User < ActiveRecord::Base | |
# ... | |
# ... | |
+ include AutoAudit | |
+ audit columns: ['first_name','last_name'] | |
# ... | |
# ... | |
diff --git a/lib/auto_audit.rb b/lib/auto_audit.rb | |
new file mode 100644 | |
index 0000000..9f3aa9e | |
--- /dev/null | |
+++ b/lib/auto_audit.rb | |
@@ -0,0 +1,48 @@ | |
+module AutoAudit | |
+ | |
+ def self.included(base) | |
+ base.cattr_accessor :audit_columns, :audit_table, :audit_polymorphic | |
+ base.extend DSL | |
+ end | |
+ | |
+ def apply_audit | |
+ changes.map{|col,vals| | |
+ if audit_columns.include?(col) | |
+ send(audit_table).create(col_name: col, before: vals.first, after: vals.last) | |
+ end | |
+ } | |
+ end | |
+ | |
+ module DSL | |
+ attr_accessor :audit_columns, :audit_table, :audit_polymorphic | |
+ def audit(opts) | |
+ options = { | |
+ polymorphic: false, | |
+ table: [table_name.singularize, 'changes'].join('_'), | |
+ columns: [] | |
+ }.merge(opts) | |
+ | |
+ self.audit_columns = options[:columns].map(&:to_s) | |
+ self.audit_table = options[:table] | |
+ self.audit_polymorphic = options[:polymorphic] | |
+ | |
+ before_update :apply_audit | |
+ has_many options[:table].to_sym | |
+ end | |
+ | |
+ def audit_all(opts) | |
+ options = { | |
+ polymorphic: false, | |
+ table: [table_name, 'changes'].join('_'), | |
+ columns: [] | |
+ }.merge(opts) | |
+ | |
+ self.audit_columns = column_names | |
+ self.audit_table = options[:table] | |
+ self.audit_polymorphic = options[:polymorphic] | |
+ | |
+ before_update :apply_audit | |
+ has_many options[:table].to_sym | |
+ end | |
+ end | |
+end | |
diff --git a/spec/lib/auto_audit_spec.rb b/spec/lib/auto_audit_spec.rb | |
new file mode 100644 | |
index 0000000..a7fcb39 | |
--- /dev/null | |
+++ b/spec/lib/auto_audit_spec.rb | |
@@ -0,0 +1,5 @@ | |
+ | |
+## I can stub out everything for the 2 models and still accurately gauge whether it is working or not. At least I thought this at some point. | |
+## | |
+## | |
+ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment