Commit ebec99ba by Michael Dilley Committed by Ryan Bigg

Add callbacks for 'new' AR lifecycle :restore

Fixes #72
parent dd8b8e12
module Paranoia module Paranoia
def self.included(klazz) def self.included(klazz)
klazz.extend Query klazz.extend Query
klazz.extend Callbacks
end end
module Query module Query
...@@ -23,6 +24,24 @@ module Paranoia ...@@ -23,6 +24,24 @@ module Paranoia
end end
end end
module Callbacks
def self.extended(klazz)
klazz.define_callbacks :restore
klazz.define_singleton_method("before_restore") do |*args, &block|
set_callback(:restore, :before, *args, &block)
end
klazz.define_singleton_method("around_restore") do |*args, &block|
set_callback(:restore, :around, *args, &block)
end
klazz.define_singleton_method("after_restore") do |*args, &block|
set_callback(:restore, :after, *args, &block)
end
end
end
def destroy def destroy
run_callbacks(:destroy) { delete } run_callbacks(:destroy) { delete }
end end
...@@ -33,7 +52,7 @@ module Paranoia ...@@ -33,7 +52,7 @@ module Paranoia
end end
def restore! def restore!
update_column :deleted_at, nil run_callbacks(:restore) { update_column :deleted_at, nil }
end end
def destroyed? def destroyed?
......
...@@ -197,6 +197,21 @@ class ParanoiaTest < Test::Unit::TestCase ...@@ -197,6 +197,21 @@ class ParanoiaTest < Test::Unit::TestCase
assert_equal 0, ParanoidModel.unscoped.where(id: model.id).count assert_equal 0, ParanoidModel.unscoped.where(id: model.id).count
end end
def test_restore_behavior_for_callbacks
model = CallbackModel.new
model.save
id = model.id
model.destroy
assert model.destroyed?
model = CallbackModel.only_deleted.find(id)
model.restore!
model.reload
assert model.instance_variable_get(:@restore_callback_called)
end
def test_real_destroy def test_real_destroy
model = ParanoidModel.new model = ParanoidModel.new
model.save model.save
...@@ -268,6 +283,7 @@ end ...@@ -268,6 +283,7 @@ end
class CallbackModel < ActiveRecord::Base class CallbackModel < ActiveRecord::Base
acts_as_paranoid acts_as_paranoid
before_destroy {|model| model.instance_variable_set :@callback_called, true } before_destroy {|model| model.instance_variable_set :@callback_called, true }
before_restore {|model| model.instance_variable_set :@restore_callback_called, true }
end end
class ParentModel < ActiveRecord::Base class ParentModel < ActiveRecord::Base
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment