Module: OptimisticallyStale

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

Defined Under Namespace

Classes: MissingLockVersion

Constant Summary collapse

VERSION =
"0.1.0"

Instance Method Summary collapse

Instance Method Details

#valid_for_update?(record:, attributes:, lock_column: :lock_version) ⇒ TrueClass

Checks if a record is valid to update, whilst enforcing optimistic locking using lock_version.

Examples:

Check a record before updating


class UpdateBook
  include Command

  def call(book:, attributes:)
    book.update(attributes)
  end

  def valid?(book:, attributes:)
    valid_for_update?(record: :book, attributes: attributes)
  end
end

book = Book.first
attributes = { lock_version: book.lock_version, title: 'new book title' }
result = UpdateBook.call(book: book, attributes: attributes)

result.successful? # => true
book.title # => 'new book title'

Because the book version has changed, another update fails


attributes[:title] = 'another title'
result = UpdateBook.call(book: book, attributes: attributes)

# => throws ActiveRecord::StaleObjectError

Returns:

  • (TrueClass)

Raises:



52
53
54
55
56
57
58
59
# File 'lib/optimistically_stale.rb', line 52

def valid_for_update?(record:, attributes:, lock_column: :lock_version)
  source_lock_version = attributes.delete(lock_column)

  raise MissingLockVersion.new(column: lock_column) unless source_lock_version.present?
  raise ActiveRecord::StaleObjectError.new(record, 'update') unless record[lock_column] == source_lock_version.to_i

  true
end