Sha256: b10668161bb879c15cf399c40c24c12b35e1d95445c0be5115f47d7aeadff9b9

Contents?: true

Size: 1.21 KB

Versions: 1

Compression:

Stored size: 1.21 KB

Contents

# -*- 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

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
mongoid_find_by-0.1.0 lib/mongoid/find_by.rb