Skip to content

Instantly share code, notes, and snippets.

@xixilive
Last active August 29, 2015 14:10
Show Gist options
  • Save xixilive/88d6e19877db81778e66 to your computer and use it in GitHub Desktop.
Save xixilive/88d6e19877db81778e66 to your computer and use it in GitHub Desktop.
Mongoid find and update, or create
# === Example
# class User
# include Mongoid::Document
# extend FindupOrCreate
#
# field :name, type: String
# field :locale, type: String
# field :password,type: String
# end
#
# # basic usage
# user = User.findup_or_create_with(:name, name: 'username', locale: 'Shanghai, China', password: RandPasswd)
# unless user.persisted?
# raise user.errors.full_messages
# else
# sign_in(user)
# end
#
# # with block
# User.findup_or_create_with(:name, name: 'username', locale: 'Shanghai, China') do |user, is_new|
# if is_new && user.errors?
# raise user.errors.full_messages
# else
# sign_in(user)
# end
# end
module FindupOrCreate
def findup_or_create_with *args, &block
attrs, keys = args.extract_options!.symbolize_keys, args.collect(&:to_sym)
new_obj, query = true, attrs.select{|k,v| args.include?(k) }
return nil if query.blank?
if obj = self.where(query).first
new_obj = false
obj.update_attributes(attrs.select{|k,v| !args.include?(k) })
end
obj ||= self.create(attrs)
yield(obj, new_obj) if block_given?
obj
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment