Module: Mongoid::Safety

Extended by:
ActiveSupport::Concern
Included in:
Components
Defined in:
lib/mongoid/safety.rb

Overview

The Safety module is used to provide a DSL to execute database operations in safe mode on a per query basis, either from the Document class level or instance level.

Defined Under Namespace

Modules: ClassMethods

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.merge_safety_options(options = {}) ⇒ Hash

Static class method of easily getting the desired safe mode options from anywhere in the framework.

Examples:

Get the options with safe mode included.

Safety.merge_safety_options({ :safe => false })

Parameters:

  • options (Hash) (defaults to: {})

    The persistence options.

Returns:

  • (Hash)

    The options hash.

Since:

  • 2.1.0



55
56
57
58
59
60
61
62
63
64
65
# File 'lib/mongoid/safety.rb', line 55

def merge_safety_options(options = {})
  options ||= {}
  return options if options[:safe]

  unless Threaded.safety_options.nil?
    safety = Threaded.safety_options
  else
    safety = Mongoid.persist_in_safe_mode
  end
  options.merge!({ :safe => safety })
end

Instance Method Details

#safely(safety = true) ⇒ Proxy

Execute the following instance-level persistence operation in safe mode.

Examples:

Upsert in safe mode.

person.safely.upsert

Destroy in safe mode with w and fsync options.

person.safely(:w => 2, :fsync => true).destroy

Parameters:

  • options (Hash)

    The safe mode options.

Returns:

  • (Proxy)

    The safety proxy.



26
27
28
# File 'lib/mongoid/safety.rb', line 26

def safely(safety = true)
  tap { Threaded.safety_options = safety }
end

#unsafelyProxy

Execute the following instance-level persistence operation without safe mode. Allows per-request overriding of safe mode when the persist_in_safe_mode config option is turned on.

Examples:

Upsert in safe mode.

person.unsafely.upsert

Returns:

  • (Proxy)

    The safety proxy.



38
39
40
# File 'lib/mongoid/safety.rb', line 38

def unsafely
  tap { Threaded.safety_options = false }
end