Skip to content
This repository has been archived by the owner on Aug 15, 2019. It is now read-only.

Commit

Permalink
Add with_attributes to override both transaction and organization ids
Browse files Browse the repository at this point in the history
  • Loading branch information
Overload119 committed Apr 26, 2013
1 parent 345b1bb commit a9f4c24
Show file tree
Hide file tree
Showing 2 changed files with 46 additions and 0 deletions.
19 changes: 19 additions & 0 deletions lib/audited/audit.rb
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ def setup_audit

before_create :set_audit_user
before_create :set_transaction_id
before_create :set_attributes

cattr_accessor :audited_class_names
self.audited_class_names = Set.new
Expand Down Expand Up @@ -45,6 +46,18 @@ def with_transaction_id(transaction_id, &block)
yieldval
end

# Override a bunch of values
def with_attributes(hash, &block)
hash.each do |key, value|
Thread.current[key] = value
end
yieldval = yield
hash.each do |key, value|
Thread.current[key] = nil
end
yieldval
end

end

# Returns a hash of the changed attributes with the new values
Expand All @@ -70,6 +83,12 @@ def set_audit_user
nil # prevent stopping callback chains
end

def set_attributes
self.transaction_id = Thread.current[:audited_transaction_id] if Thread.current[:audited_transaction_id]
self.organization_id = Thread.current[:audited_organization_id] if Thread.current[:audited_organization_id]
nil
end

def set_transaction_id
self.transaction_id = Thread.current[:audited_transaction_id] if Thread.current[:audited_transaction_id]
nil
Expand Down
27 changes: 27 additions & 0 deletions spec/audited/adapters/active_record/audit_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -106,7 +106,34 @@ class Models::ActiveRecord::CustomUserSubclass < Models::ActiveRecord::CustomUse
tr
end.should == tr
end
end

describe "with_attributes" do
let(:tr) { SecureRandom.hex(32) }
let(:org) { 123 }

it "should record transaction ids" do
attributes = {
:audited_transaction_id => tr,
:audited_organization_id => org
}
Audited.audit_class.with_attributes(attributes) do
company = Models::ActiveRecord::Company.create :name => 'The auditors'
company.name = 'The Auditors, Inc'
company.save

company.audits.each do |audit|
audit.transaction_id.should == tr
audit.organization_id.should == org
end
end
end

it "should return the value from the yield block" do
Audited.audit_class.with_transaction_id(tr) do
tr
end.should == tr
end
end

describe "as_user" do
Expand Down

0 comments on commit a9f4c24

Please sign in to comment.