Module: Mongoid::Finders

Defined in:
lib/mongoid_dynamic_finder/finder.rb

Instance Method Summary collapse

Dynamic Method Handling

This class handles dynamic methods through the method_missing method

#method_missing(method_id, *args, &block) ⇒ Object



4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
# File 'lib/mongoid_dynamic_finder/finder.rb', line 4

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
    super
  end
end