module MongoidCleaner

MongoidCleaner base module

Constants

VERSION

Attributes

strategy[R]

Public Class Methods

available_strategies() click to toggle source
# File lib/mongoid_cleaner.rb, line 15
def available_strategies
  @available_strategies ||= %w(truncate drop)
end
clean() click to toggle source

call truncate or drop method

# File lib/mongoid_cleaner.rb, line 86
def clean
  public_send strategy
end
cleaning() { || ... } click to toggle source
# File lib/mongoid_cleaner.rb, line 90
def cleaning
  clean
  yield if block_given?
end
collections() click to toggle source

@return Array mongoid collections names

# File lib/mongoid_cleaner.rb, line 51
def collections
  if mongoid_version > 4
    collections_filter.first[:cursor][:firstBatch].map { |c| c['name'] }
  else
    collections_filter['cursor']['firstBatch'].map { |c| c['name'] }
  end
end
collections_filter() click to toggle source

return with mongoid 5 ‘Mongo::Operation::Result` return with mongoid 4 `BSON::Document`

# File lib/mongoid_cleaner.rb, line 41
def collections_filter
  session.command(
    listCollections: 1,
    filter: {
      name:
      { '$not' => /.?system\.|\$/ }
    })
end
collections_with_options() click to toggle source
# File lib/mongoid_cleaner.rb, line 59
def collections_with_options
  return collections unless @options
  return collections if @options.empty?
  if @options[:only]
    collections.select { |c| @options[:only].include? c }
  elsif @options[:except]
    collections.select { |c| !@options[:except].include? c }
  end
end
drop() click to toggle source

@return Boolean

# File lib/mongoid_cleaner.rb, line 70
def drop
  collections_with_options.each { |c| session[c].drop }
  true
end
mongoid_version() click to toggle source
# File lib/mongoid_cleaner.rb, line 11
def mongoid_version
  @mongoid_version ||= Mongoid::VERSION.split('.').first.to_i
end
session() click to toggle source
# File lib/mongoid_cleaner.rb, line 31
def session
  @session ||= if mongoid_version > 4
                 Mongoid.default_client
               else
                 Mongoid.default_session
               end
end
strategy=(*options) click to toggle source

@arg args strategy String @arg args options Hash

# File lib/mongoid_cleaner.rb, line 21
def strategy=(*options)
  strategy = options.flatten.shift.to_s
  @options = options.flatten.last if options.flatten.last.is_a? Hash
  if available_strategies.include? strategy
    @strategy = strategy
  else
    fail UnknownStrategySpecified
  end
end
truncate() click to toggle source

@return Boolean

# File lib/mongoid_cleaner.rb, line 76
def truncate
  if mongoid_version > 4
    collections_with_options.each { |c| session[c].find.delete_many }
  else
    collections_with_options.each { |c| session[c].find.remove_all }
  end
  true
end