Sha256: c6cce56739542da9c131979076a2a1ea98f707c18663e0f94215aac88749d951

Contents?: true

Size: 1.18 KB

Versions: 1

Compression:

Stored size: 1.18 KB

Contents

# frozen_string_literal: true
module DatabaseFlusher
  module Mongoid
    class DeletionStrategy
      attr_reader :collections

      class Subscriber
        def initialize(strategy)
          @strategy = strategy
        end

        def started(event)
          if event.command_name == :insert || event.command_name == 'insert'.freeze
            collection = event.command['insert'.freeze]
            if collection
              @strategy.collections << collection
            end
          end
        end

        private

        def method_missing(*args, &block)
        end
      end

      def initialize
        @collections = Set.new
      end

      def start
        @subscriber ||= Mongo::Monitoring::Global.subscribe(
          Mongo::Monitoring::COMMAND,
          Subscriber.new(self)
        )
      end

      def stop
        raise NotImplementedError, "Mongo doesn't provide unsubscribe"
      end

      def clean
        return if collections.empty?
        # puts "Cleaning #{collections.inspect}"
        client = ::Mongoid::Clients.default
        collections.each do |name|
          client[name].delete_many
        end
        collections.clear
      end
    end
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
database_flusher-0.2.3 lib/database_flusher/mongoid/deletion_strategy.rb