Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add support for undoing changes #381

Merged
merged 1 commit into from
Dec 30, 2017
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 19 additions & 0 deletions lib/audited/audit.rb
Original file line number Diff line number Diff line change
Expand Up @@ -86,6 +86,25 @@ def old_attributes
end
end

# Allows user to undo changes
def undo
model = self.auditable_type.constantize
if action == 'create'
# destroys a newly created record
model.find(auditable_id).destroy!
elsif action == 'destroy'
# creates a new record with the destroyed record attributes
model.create(audited_changes)
else
# changes back attributes
audited_object = model.find(auditable_id)
self.audited_changes.each do |k, v|
audited_object[k] = v[0]
end
audited_object.save
end
end

# Allows user to be set to either a string or an ActiveRecord object
# @private
def user_as_string=(user)
Expand Down
22 changes: 22 additions & 0 deletions spec/audited/audit_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,28 @@ class TempModel < ::ActiveRecord::Base
end
end

it "should undo changes" do
user = Models::ActiveRecord::User.create(name: "John")
user.update_attribute(:name, 'Joe')
user.audits.last.undo
user.reload

expect(user.name).to eq("John")
end

it "should undo destroyed model" do
user = Models::ActiveRecord::User.create(name: "John")
user.destroy
user.audits.last.undo
user = Models::ActiveRecord::User.find_by(name: "John")
expect(user.name).to eq("John")
end

it "should undo created model" do
user = Models::ActiveRecord::User.create(name: "John")
expect {user.audits.last.undo}.to change(Models::ActiveRecord::User, :count).by(-1)
end

context "when a custom audit class is not configured" do
it "should default to #{described_class}" do
TempModel.audited
Expand Down