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

Prevent model callbacks if deactivated #1

Open
wants to merge 2 commits into
base: prevent_enqueue_if_deactivated
Choose a base branch
from
Open
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
2 changes: 1 addition & 1 deletion lib/meilisearch-rails.rb
Original file line number Diff line number Diff line change
Expand Up @@ -418,7 +418,7 @@ def meilisearch(options = {}, &block)
proc.call(record, remove) if ::MeiliSearch::Rails.active? && !ms_without_auto_index_scope
end
end
unless options[:auto_index] == false
if ::MeiliSearch::Rails.active? && options[:auto_index] != false
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

There is actually no way to prevent creating callbacks when meilisearch is disabled without significant restructuring.

The problem lies in the fact that Meilisearch can be deactivated after it was started as active. The active configuration is dynamic.

So while this change avoids creating the callbacks when Meilisearch is started in an inactive state, it does not prevent the callbacks from being run when Meilisearch starts enabled and then gets disabled.

It also does not have a mechanism to add the callbacks when Meilisearch starts disabled and gets enabled.

Essentially, since the active state is dynamic, it makes sense to be lazy and defer deciding whether or not to index during the callback even if it incurs a performance cost.

You can add this check inside the callback but I would not expect a large performance difference since when Meilisearch is disabled every method call on it is basically a noop.

if defined?(::Sequel::Model) && self < Sequel::Model
class_eval do
copy_after_validation = instance_method(:after_validation)
Expand Down
9 changes: 9 additions & 0 deletions spec/meilisearch/activation_spec.rb
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
require 'support/models/queued_models'
require 'support/models/movie'

describe MeiliSearch::Rails do
it 'is active by default' do
Expand All @@ -24,6 +25,14 @@
EnqueuedDocument.create! name: 'hello world'
end.not_to raise_error
end

it 'does not run callbacks on save' do
movie = Movie.new(title: 'Harry Potter')
allow(movie).to receive(:ms_index!)
movie.save

expect(movie).not_to have_received(:ms_index!)
end
end

context 'with a block' do
Expand Down