Skip to content

Instantly share code, notes, and snippets.

@Stex
Created Aug 13, 2013
Embed
What would you like to do?
Adds lock/unlock functionality to a Ruby on Rails model using a deleted_at column in the corresponding table. To use it, simply "include Lockable" in your model (Rails 2.3, for Rails 3 change named_scope to scope)
module Lockable
def self.included(base)
base.class_eval do
named_scope :not_locked, :conditions => {:deleted_at => nil}
named_scope :locked, :conditions => "#{table_name}.deleted_at IS NOT NULL"
end
end
# Locks the record by setting the deleted_at attribute
# to the current time.
# Triggers the +before_lock+ callback if defined.
# If this callback returns false, the record is not locked!
# Triggers the +after_lock+ callback if it is defined.
#--------------------------------------------------------------
def lock
self.deleted_at = Time.now
if !self.respond_to?(:before_lock) || self.before_lock
if self.save(false)
self.after_lock if self.respond_to?(:after_lock)
end
end
end
# Unlocks the given record by clearing the deleted_at attribute
# Notice: When unlocking records, validations are executed
# to make sure that no invalid unlocked records exist.
# Triggers the +after_unlock+ callback if it is defined
# Triggers the +before_unlock+ callback if it is defined.
# If this callback returns false, the record is not unlocked!
#--------------------------------------------------------------
def unlock
self.deleted_at = nil
if !self.respond_to?(:before_unlock) || self.before_unlock
if self.save
self.after_unlock if self.respond_to?(:after_unlock)
end
end
end
def locked?
!self.deleted_at.nil?
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment