Sha256: 75f7760466a0c2957a48aab7ddcdac1c28420d33ea3e36fdbb5ef2b85f933462

Contents?: true

Size: 1.42 KB

Versions: 2

Compression:

Stored size: 1.42 KB

Contents

module DatabaseRewinder
  class Cleaner
    attr_accessor :db, :connection_name, :inserted_tables, :pool

    def initialize(db: nil, connection_name: nil, only: nil, except: nil)
      @db, @connection_name, @only, @except = db, connection_name, Array(only), Array(except)
      reset
    end

    def clean
      return unless pool
      return if inserted_tables.empty?

      delete_all (ar_conn = pool.connection), DatabaseRewinder.all_table_names(ar_conn) & inserted_tables
      reset
    end

    def clean_all
      return unless pool

      delete_all (ar_conn = pool.connection), DatabaseRewinder.all_table_names(ar_conn)
      reset
    end

    def clean_with(_strategy, only: nil, except: nil, **)
      @only += Array(only) unless only.blank?
      @except += Array(except) unless except.blank?
      clean_all
    end

    # for database_cleaner compat
    def strategy=(_strategy, only: nil, except: nil, **)
      @only += Array(only) unless only.blank?
      @except += Array(except) unless except.blank?
    end

    private
    def delete_all(ar_conn, tables)
      tables = tables & @only if @only.any?
      tables -= @except if @except.any?
      return if tables.empty?

      ar_conn.disable_referential_integrity do
        tables.each do |table_name|
          ar_conn.execute "DELETE FROM #{ar_conn.quote_table_name(table_name)};"
        end
      end
    end

    def reset
      @inserted_tables = []
    end
  end
end

Version data entries

2 entries across 2 versions & 1 rubygems

Version Path
database_rewinder-0.0.2 lib/database_rewinder/cleaner.rb
database_rewinder-0.0.1 lib/database_rewinder/cleaner.rb