Sha256: 18a334c7c1c4854deffd21a78ae85fa38e838f4402b5e7b5e2d3112a36a38c48

Contents?: true

Size: 1.02 KB

Versions: 3

Compression:

Stored size: 1.02 KB

Contents

# -*- encoding : utf-8 -*-
module Mongoid
  module FindBy
    extend ActiveSupport::Concern
    autoload :Version, 'mongoid/find_by/version'

    included do
    end
    
    module ClassMethods
      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
            super
        end
      end 
    end
  end
end

Version data entries

3 entries across 3 versions & 1 rubygems

Version Path
mongoid_find_by-0.1.3 lib/mongoid/find_by.rb
mongoid_find_by-0.1.2 lib/mongoid/find_by.rb
mongoid_find_by-0.1.1 lib/mongoid/find_by.rb