Skip to content

Commit

Permalink
Allow use of deletion callback for rollback events.
Browse files Browse the repository at this point in the history
Related to #1021.
  • Loading branch information
pat committed Sep 10, 2017
1 parent 1be2d80 commit ec35be9
Show file tree
Hide file tree
Showing 2 changed files with 70 additions and 3 deletions.
14 changes: 11 additions & 3 deletions lib/thinking_sphinx/active_record/callbacks/delete_callbacks.rb
@@ -1,18 +1,26 @@
class ThinkingSphinx::ActiveRecord::Callbacks::DeleteCallbacks <
ThinkingSphinx::Callbacks

callbacks :after_destroy
callbacks :after_destroy, :after_rollback

def after_destroy
delete_from_sphinx
end

def after_rollback
delete_from_sphinx
end

private

def delete_from_sphinx
return if ThinkingSphinx::Callbacks.suspended? || instance.new_record?

indices.each { |index|
ThinkingSphinx::Deletion.perform index, instance.id
}
end

private

def indices
ThinkingSphinx::Configuration.instance.index_set_class.new(
:classes => [instance.class]
Expand Down
Expand Up @@ -64,4 +64,63 @@
ThinkingSphinx::Callbacks.resume!
end
end

describe '.after_rollback' do
let(:callbacks) { double('callbacks', :after_rollback => nil) }

before :each do
allow(ThinkingSphinx::ActiveRecord::Callbacks::DeleteCallbacks).
to receive_messages :new => callbacks
end

it "builds an object from the instance" do
expect(ThinkingSphinx::ActiveRecord::Callbacks::DeleteCallbacks).
to receive(:new).with(instance).and_return(callbacks)

ThinkingSphinx::ActiveRecord::Callbacks::DeleteCallbacks.
after_rollback(instance)
end

it "invokes after_rollback on the object" do
expect(callbacks).to receive(:after_rollback)

ThinkingSphinx::ActiveRecord::Callbacks::DeleteCallbacks.
after_rollback(instance)
end
end

describe '#after_rollback' do
let(:index_set) { double 'index set', :to_a => [index] }
let(:index) { double('index', :name => 'foo_core',
:document_id_for_key => 14, :type => 'plain', :distributed? => false) }
let(:instance) { double('instance', :id => 7, :new_record? => false) }

before :each do
allow(ThinkingSphinx::IndexSet).to receive_messages :new => index_set
end

it "performs the deletion for the index and instance" do
expect(ThinkingSphinx::Deletion).to receive(:perform).with(index, 7)

callbacks.after_rollback
end

it "doesn't do anything if the instance is a new record" do
allow(instance).to receive_messages :new_record? => true

expect(ThinkingSphinx::Deletion).not_to receive(:perform)

callbacks.after_rollback
end

it 'does nothing if callbacks are suspended' do
ThinkingSphinx::Callbacks.suspend!

expect(ThinkingSphinx::Deletion).not_to receive(:perform)

callbacks.after_rollback

ThinkingSphinx::Callbacks.resume!
end
end
end

0 comments on commit ec35be9

Please sign in to comment.