# -*- encoding : utf-8 -*- module Mongoid module FindBy extend ActiveSupport::Concern autoload :Version, 'mongoid/find_by/version' included do old_method_missing = if methods(false).member? :method_missing method(:method_missing) end 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 == '!' tokens = $2.split(/_and_/) raise ArgumentError, 'Attributes and arguments does\'nt match' if tokens.size != args.size tokens.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 if old_method_missing old_method_missing.bind(self).call else super end end end end end end