Skip to content

Instantly share code, notes, and snippets.

@abriening
Created July 6, 2010 22:46
Show Gist options
  • Save abriening/466039 to your computer and use it in GitHub Desktop.
Save abriening/466039 to your computer and use it in GitHub Desktop.
module UpdatedAtLocking
def self.included(base)
base.alias_method_chain :update, :stale_object_detection
base.class_inheritable_accessor :updated_at_locking_enabled, :instance_writer => false
base.updated_at_locking_enabled = true
end
def updated_at_locking_enabled?
self.updated_at_locking_enabled == true
end
##
# Checks if the updated_at was set to a different value that is less than the saved value.
# Raises ActiveRecord::StaleObjectError like Optimistic locking update.
#
def raise_if_stale_object
if updated_at && updated_at_was && (updated_at.to_s(:db) < updated_at_was.to_s(:db))
raise ActiveRecord::StaleObjectError,
"Attempted to update a stale object. Record was last updated at #{updated_at_was}"
end
end
##
# Overrides update, could not be a before_filter without setting record_timestamps to false and reimplementing timestamping.
# This is because the update_with_timestamps is called before update_with_callbacks.
#
def update_with_stale_object_detection(*args)
updated_at_locking_enabled? && raise_if_stale_object
update_without_stale_object_detection(*args)
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment