Last active
December 13, 2015 20:38
-
-
Save foreverman/4970888 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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