Module: Mongoid::Locker::ClassMethods

Defined in:
lib/mongoid/locker.rb

Instance Method Summary collapse

Instance Method Details

#lockedMongoid::Criteria

A scope to retrieve all locked documents in the collection.

Examples:

Account.count
#=> 1717
Account.locked.count
#=> 17

Returns:

  • (Mongoid::Criteria)


137
138
139
140
141
142
143
144
145
# File 'lib/mongoid/locker.rb', line 137

def locked
  where(
    '$and': [
      { locking_name_field => { '$exists': true, '$ne': nil } },
      { locked_at_field => { '$exists': true, '$ne': nil } },
      { '$where': "new Date() - this.#{locked_at_field} < #{lock_timeout * 1000}" }
    ]
  )
end

#locker(**params) ⇒ Object

Sets configuration for this class.

Examples:

locker locking_name_field: :locker_locking_name,
       locked_at_field: :locker_locked_at,
       lock_timeout: 3,
       locker_write_concern: { w: 1 },
       maximum_backoff: 30.0,
       backoff_algorithm: :locked_at_backoff,
       locking_name_generator: :custom_locking_name

Parameters:

  • locking_name_field (Symbol)
  • locked_at_field (Symbol)
  • maximum_backoff (Float, Integer)
  • lock_timeout (Float, Integer)
  • locker_write_concern (Hash)
  • backoff_algorithm (Symbol)
  • locking_name_generator (Symbol)

Raises:



209
210
211
212
213
214
215
216
# File 'lib/mongoid/locker.rb', line 209

def locker(**params)
  invalid_parameters = params.keys - Mongoid::Locker.singleton_class.const_get('MODULE_METHODS')
  raise Mongoid::Locker::Errors::InvalidParameter.new(self.class, invalid_parameters.first) unless invalid_parameters.empty?

  params.each_pair do |key, value|
    send("#{key}=", value)
  end
end

#unlock_allInteger

Unlock all locked documents in the collection. Sets locking_name_field and locked_at_field fields to nil. Returns number of unlocked documents.

Examples:

Account.unlock_all
#=> 17
Account.locked.unlock_all
#=> 0

Returns:

  • (Integer)


187
188
189
# File 'lib/mongoid/locker.rb', line 187

def unlock_all
  update_all('$set': { locking_name_field => nil, locked_at_field => nil }).modified_count
end

#unlockedMongoid::Criteria

A scope to retrieve all unlocked documents in the collection.

Examples:

Account.count
#=> 1717
Account.unlocked.count
#=> 1700

Returns:

  • (Mongoid::Criteria)


156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
# File 'lib/mongoid/locker.rb', line 156

def unlocked
  where(
    '$or': [
      {
        '$or': [
          { locking_name_field => { '$exists': false } },
          { locked_at_field => { '$exists': false } }
        ]
      },
      {
        '$or': [
          { locking_name_field => { '$eq': nil } },
          { locked_at_field => { '$eq': nil } }
        ]
      },
      {
        '$where': "new Date() - this.#{locked_at_field} >= #{lock_timeout * 1000}"
      }
    ]
  )
end