Created
November 21, 2011 06:23
-
-
Save iwinux/1381824 to your computer and use it in GitHub Desktop.
add find_by_attribute to Mongoid
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
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