Module: MongoidCleaner

Defined in:
lib/mongoid_cleaner.rb,
lib/mongoid_cleaner/version.rb

Overview

:nodoc:

Defined Under Namespace

Classes: UnknownStrategySpecified

Constant Summary collapse

VERSION =
'1.2.0'

Class Attribute Summary collapse

Class Method Summary collapse

Class Attribute Details

.strategyObject

Returns the value of attribute strategy.



9
10
11
# File 'lib/mongoid_cleaner.rb', line 9

def strategy
  @strategy
end

Class Method Details

.available_strategiesObject



15
16
17
# File 'lib/mongoid_cleaner.rb', line 15

def available_strategies
  @available_strategies ||= %w(truncate drop)
end

.cleanObject

call truncate or drop method



86
87
88
# File 'lib/mongoid_cleaner.rb', line 86

def clean
  public_send strategy
end

.cleaningObject



90
91
92
93
# File 'lib/mongoid_cleaner.rb', line 90

def cleaning
  clean
  yield if block_given?
end

.collectionsObject

Returns Array mongoid collections names.

Returns:

  • Array mongoid collections names



51
52
53
54
55
56
57
# 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_filterObject

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



41
42
43
44
45
46
47
48
# File 'lib/mongoid_cleaner.rb', line 41

def collections_filter
  session.command(
    listCollections: 1,
    filter: {
      name:
      { '$not' => /.?system\.|\$/ }
    })
end

.collections_with_optionsObject



59
60
61
62
63
64
65
66
67
# 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

.dropObject

Returns Boolean.

Returns:

  • Boolean



70
71
72
73
# File 'lib/mongoid_cleaner.rb', line 70

def drop
  collections_with_options.each { |c| session[c].drop }
  true
end

.mongoid_versionObject



11
12
13
# File 'lib/mongoid_cleaner.rb', line 11

def mongoid_version
  @mongoid_version ||= Mongoid::VERSION.split('.').first.to_i
end

.sessionObject



31
32
33
34
35
36
37
# File 'lib/mongoid_cleaner.rb', line 31

def session
  @session ||= if mongoid_version > 4
                 Mongoid.default_client
               else
                 Mongoid.default_session
               end
end

.truncateObject

Returns Boolean.

Returns:

  • Boolean



76
77
78
79
80
81
82
83
# 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