Skip to content

Instantly share code, notes, and snippets.

@prdanelli
Last active February 1, 2022 13:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save prdanelli/c2cce7c1403488917d16b3f3bbee9fe8 to your computer and use it in GitHub Desktop.
Save prdanelli/c2cce7c1403488917d16b3f3bbee9fe8 to your computer and use it in GitHub Desktop.
Decorate class with extend/prepend

Decorate class with extend/prepend

Update indexed instance after blob analyzed

# app/jobs/active_storage/analyze_job_decorator.rb
module ActiveStorage::AnalyzeJobDecorator
  def self.prepended(base)
    base.around_perform do |job, block|
      block.call

      blob = job.arguments.first
      blob.reload.attachments.each do |attachment|
        next unless attachment.record.respond_to?(:reindex)

        Searchkick::RecordIndexer.new(attachment.record).reindex
      end
    end
  end

  ::ActiveStorage::AnalyzeJob.prepend(self)
end
# app/models/active_storage/blob_decorator.rb
  # ...
  end
  
  def self.prepended(base)
    base.after_commit :reindex_attachment_records, only: :update
  end

  def reindex_attachment_records
    return unless saved_change_to_metadata?

    attachments.each do |attachment|
      next unless attachment.record.respond_to?(:reindex)
      
      Searchkick::RecordIndexer.new(attachment.record).reindex
    end
  end

  ::ActiveStorage::Blob.extend(ClassMethods)
  ::ActiveStorage::Blob.prepend(self)
end
# config/application.rb
config.to_prepare do
  Dir.glob(Rails.root.join('app/**/*_decorator*.rb')) do |path|
    require_dependency(path)
  end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment