public
Created

  • Download Gist
find_by.rb
Ruby
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49
##
#
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

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.