Created
January 22, 2012 15:54
-
-
Save ahoward/1657500 to your computer and use it in GitHub Desktop.
This file contains 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
## | |
# | |
def self.not_found!(*args) | |
options = args.extract_options!.to_options! | |
ids = args | |
message = (ids.blank? and !options.blank?) ? options.inspect : nil | |
ids.push(nil) if ids.blank? | |
e = ::Mongoid::Errors::DocumentNotFound.new(self, *ids) | |
e.message.gsub!(/id\(s\).*$/, message) if message | |
raise(e) | |
end | |
def not_found!(*args) | |
self.class.not_found!(*args) | |
end | |
## finders | |
# | |
def self.find_by(conditions) | |
where(conditions).first | |
end | |
def self.find_by!(conditions) | |
find_by(conditions) or not_found!(conditions) | |
end | |
def self.create_or_update(*args) | |
attributes = args.shift | |
conditions = args.shift || attributes | |
created = false | |
doc = find(:first, :conditions => conditions) | |
doc ||= ( | |
begin | |
(created = create!(attributes)) | |
rescue | |
find(:first, :conditions => conditions) or | |
(created = create!(attributes)) | |
end | |
) | |
doc.update_attributes(attributes) unless created | |
doc | |
end | |
def self.create_or_update!(*args) | |
create_or_update(*args) || not_found!(*args) | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment