Class: Chewy::Strategy::LazySidekiq

Inherits:
Sidekiq show all
Defined in:
lib/chewy/strategy/lazy_sidekiq.rb

Overview

The strategy works the same way as sidekiq, but performs async evaluation of all index callbacks on model create and update driven by sidekiq

Chewy.strategy(:lazy_sidekiq) do User.all.map(&:save) # Does nothing here Post.all.map(&:save) # And here # It schedules import of all the changed users and posts right here end

Defined Under Namespace

Classes: IndicesUpdateWorker

Instance Method Summary collapse

Methods inherited from Atomic

#update

Methods inherited from Base

#name, #update

Constructor Details

#initializeLazySidekiq

Returns a new instance of LazySidekiq.



32
33
34
35
36
37
38
39
40
41
42
# File 'lib/chewy/strategy/lazy_sidekiq.rb', line 32

def initialize
  # Use parent's @stash to store destroyed records, since callbacks for them have to
  # be run immediately on the strategy block end because we won't be able to fetch
  # records further in IndicesUpdateWorker. This will be done by avoiding of
  # LazySidekiq#update_chewy_indices call and calling LazySidekiq#update instead.
  super

  # @lazy_stash is used to store all the lazy evaluated callbacks with call of
  # strategy's #update_chewy_indices.
  @lazy_stash = {}
end

Instance Method Details

#leaveObject



44
45
46
47
48
49
50
51
52
53
54
55
56
# File 'lib/chewy/strategy/lazy_sidekiq.rb', line 44

def leave
  # Fallback to Sidekiq#leave implementation for destroyed records stored in @stash.
  super

  # Proceed with other records stored in @lazy_stash
  return if @lazy_stash.empty?

  ::Sidekiq::Client.push(
    'queue' => sidekiq_queue,
    'class' => Chewy::Strategy::LazySidekiq::IndicesUpdateWorker,
    'args'  => [@lazy_stash]
  )
end

#update_chewy_indices(object) ⇒ Object



58
59
60
61
# File 'lib/chewy/strategy/lazy_sidekiq.rb', line 58

def update_chewy_indices(object)
  @lazy_stash[object.class.name] ||= []
  @lazy_stash[object.class.name] |= Array.wrap(object.id)
end