Skip to content

Commit

Permalink
Allow nested as_user auditing (collectiveidea#450)
Browse files Browse the repository at this point in the history
  • Loading branch information
KevinColemanInc authored and tbrisker committed Jun 17, 2018
1 parent 88f2779 commit 46e560d
Show file tree
Hide file tree
Showing 3 changed files with 23 additions and 1 deletion.
2 changes: 2 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,8 @@ Added
[#426](https://github.com/collectiveidea/audited/pull/426)
- Add `own_and_associated_audits` method to auditable models
[#428](https://github.com/collectiveidea/audited/pull/428)
- Ability to nest `as_user` within itself
[#450](https://github.com/collectiveidea/audited/pull/450)

Changed

Expand Down
3 changes: 2 additions & 1 deletion lib/audited/audit.rb
Original file line number Diff line number Diff line change
Expand Up @@ -131,10 +131,11 @@ def self.audited_classes
# by +user+. This method is hopefully threadsafe, making it ideal
# for background operations that require audit information.
def self.as_user(user, &block)
last_audited_user = ::Audited.store[:audited_user]
::Audited.store[:audited_user] = user
yield
ensure
::Audited.store[:audited_user] = nil
::Audited.store[:audited_user] = last_audited_user
end

# @private
Expand Down
19 changes: 19 additions & 0 deletions spec/audited/audit_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -215,6 +215,25 @@ class Models::ActiveRecord::CustomUserSubclass < Models::ActiveRecord::CustomUse
end
end

it "should support nested as_user" do
Audited::Audit.as_user("sidekiq") do
company = Models::ActiveRecord::Company.create name: "The auditors"
company.name = "The Auditors, Inc"
company.save
expect(company.audits[-1].user).to eq("sidekiq")

Audited::Audit.as_user(user) do
company.name = "NEW Auditors, Inc"
company.save
expect(company.audits[-1].user).to eq(user)
end

company.name = "LAST Auditors, Inc"
company.save
expect(company.audits[-1].user).to eq("sidekiq")
end
end

it "should record usernames" do
Audited::Audit.as_user(user.name) do
company = Models::ActiveRecord::Company.create name: "The auditors"
Expand Down

0 comments on commit 46e560d

Please sign in to comment.