Skip to content

Instantly share code, notes, and snippets.

@ahoward
Created January 22, 2012 15:54
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 ahoward/1657500 to your computer and use it in GitHub Desktop.
Save ahoward/1657500 to your computer and use it in GitHub Desktop.
##
#
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