Skip to content

Instantly share code, notes, and snippets.

@foreverman
Last active December 13, 2015 20:38
Show Gist options
  • Save foreverman/4970888 to your computer and use it in GitHub Desktop.
Save foreverman/4970888 to your computer and use it in GitHub Desktop.
# a module to make insertions and updates serializable given the unique keys/fields
# a unique constraint have to be created based the keys
module Serializable
EXCEPTIONS = [
ActiveRecord::StaleObjectError, ActiveRecord::StatementInvalid,
ActiveRecord::RecordNotUnique
]
def self.included(base_class)
base_class.extend(ClassMethods)
end
module ClassMethods
def with(keys, &proc)
object = where(keys).first || new(keys)
proc.call(object)
object.save!
rescue *EXCEPTIONS
retry
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment