Module: Sequel::Plugins::InstanceFilters

Defined in:


This plugin allows you to add filters on a per object basis that restrict updating or deleting the object. It's designed for cases where you would normally have to drop down to the dataset level to get the necessary control, because you only want to delete or update the rows in certain cases based on the current status of the row in the database. The main purpose of this plugin is to avoid race conditions by relying on the atomic properties of database transactions.

class Item < Sequel::Model
  plugin :instance_filters

# These are two separate objects that represent the same
# database row. 
i1 = Item.first(id: 1, delete_allowed: false)
i2 = Item.first(id: 1, delete_allowed: false)

# Add an instance filter to the object. This filter is in effect
# until the object is successfully updated or deleted.
i1.instance_filter(delete_allowed: true)

# Attempting to delete the object where the filter doesn't
# match any rows raises an error.
i1.delete # raises Sequel::NoExistingObject

# The other object that represents the same row has no
# instance filters, and can be updated normally.
i2.update(delete_allowed: true)

# Even though the filter is now still in effect, since the
# database row has been updated to allow deleting,
# delete now works.

This plugin sets the require_modification flag on the model, so if the model's dataset doesn't provide an accurate number of matched rows, this could result in invalid exceptions being raised.

Defined Under Namespace

Modules: InstanceMethods

Constant Summary collapse

Error =

Exception class raised when updating or deleting an object does not affect exactly one row.


Class Method Summary collapse

Class Method Details

.configure(model) ⇒ Object

Set the require_modification flag to true for the model.

# File 'lib/sequel/plugins/instance_filters.rb', line 49

def self.configure(model)
  model.require_modification = true