Skip to content

Instantly share code, notes, and snippets.

@iwinux
Created November 21, 2011 06:23
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 iwinux/1381824 to your computer and use it in GitHub Desktop.
Save iwinux/1381824 to your computer and use it in GitHub Desktop.
add find_by_attribute to Mongoid
module Mongoid
module Finders
# add find_by_xxx to Mongoid
# from https://github.com/mitijain123/mongoid/commit/b28b360b787ba4cd32e5423afcfa3b83574f9df1
def method_missing(method_id, *args, &block)
conditions = {}
bang = false
case method_id.to_s
when /^find_(all|last||first)_?by_([_a-zA-Z]\w*)(!?)$/
finder_type = $1.blank? ? :first : $1.to_sym
bang = true if $3 == '!'
$2.split(/_and_/).each_with_index do |attr, i|
conditions[attr] = args[i]
end
result = find(finder_type, :conditions => conditions)
if result.nil? and bang
raise Mongoid::Errors::DocumentNotFound.new(self.class, args)
else
return result
end
else
nil
end
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment