0

In a Rails app Chewy gem is used to handle ElasticSearch indexing. I have a block of code in an after_commit and I need it to be run once a new record of the RDB is indexed in our NRDB. it looks like:

class User < ApplicationRecord

   update_index('USER') { self }

   after_commit :run_this_block, on: :create


   def run_this_block
     index = UsersIndex.find id
     'do something with index'
   end
end

seems the after_commit is called before update_index!!! Nothing is found in chewy gem, Anyone with any idea?

1 Answers1

0

That could be a possible solution, though it doesn’t work in my specific case:

There is leave method in atomic strategy of Chewy which let bypass the main atomic update_index action:

 class Atomic < Base
      def initialize
        @stash = {}
      end

      def update(type, objects, _options = {})
        @stash[type] ||= []
        @stash[type] |= type.root.id ? Array.wrap(objects) : type.adapter.identify(objects)
      end

      def leave
        @stash.all? { |type, ids| type.import!(ids) }
      end
    end

It is possible to prepend leave method in chewy.rb:

# /config/initializers/chewy.rb

Chewy::Strategy::Atomic.prepend(
  Module.new do
    def leave
      @stash.all? do |type, ids|
        if INTENDED_INDICES_NAMES.include?(type.name)
            type.import!(sliced_ids)
            <here goes the code where one have access to recently indexed records>
        else
          type.import!(ids)
        end
        true
      end
    end
   end