Module: DataMapper::Lock::Optimistic

Defined in:
lib/dm-lock/optimistic.rb

Defined Under Namespace

Modules: ClassMethods

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.included(model) ⇒ Object

Validate model’s lock_version before attempting to save or destroy.



10
11
12
13
14
15
# File 'lib/dm-lock/optimistic.rb', line 10

def self.included model
  model.extend ClassMethods
  model.before :destroy, :validate_lock_version
  model.before :save, :validate_lock_version
  model.before :save, :increment_lock_version
end

Instance Method Details

#increment_lock_versionObject

Increment the lock_version.



49
50
51
# File 'lib/dm-lock/optimistic.rb', line 49

def increment_lock_version
  self.lock_version += 1
end

#lock_version_altered?Boolean

Check if the lock_version has been altered and return the latest record.

Returns:

  • (Boolean)


41
42
43
44
# File 'lib/dm-lock/optimistic.rb', line 41

def lock_version_altered?
  @latest_record = self.class.get original_attributes[:id] || id
  @latest_record.lock_version != lock_version
end

#validate_lock_versionObject

Validate the lock version.

* Lets new records passed
* Lets un-altered records passed
* Lets the record pass unless the lock_version has been changed

Raises

DataMapper::Lock::StaleRecordError


29
30
31
32
33
34
35
# File 'lib/dm-lock/optimistic.rb', line 29

def validate_lock_version
  if !new? && dirty?
    if lock_version_altered?
      raise DataMapper::Lock::StaleRecordError.new(self, @latest_record)
    end
  end
end