Skip to content

Instantly share code, notes, and snippets.

@careo
Created March 16, 2010 19:24
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save careo/334385 to your computer and use it in GitHub Desktop.
Save careo/334385 to your computer and use it in GitHub Desktop.
module OptimisticLocking
class StaleObjectError < Exception
end
def update
dirty_attributes = self.dirty_attributes
return true if dirty_attributes.empty?
count = repository.update(dirty_attributes, to_query)
if count == 1
return true
else
raise StaleObjectError
end
end
# hackery to get the timestamp into the update clause
def to_query(query = {})
qry = super
unless self.new?
lock_version = self.original_attributes[:timestamp]
if lock_version
qry.send(:append_condition, :timestamp, lock_version)
end
end
qry
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment