Module: Mongoid::SimpleFinders::ClassMethods

Defined in:
lib/mongoid_misc/simple_finders.rb

Instance Method Summary collapse

Dynamic Method Handling

This class handles dynamic methods through the method_missing method

#method_missing(clause, *a, &b) ⇒ Object



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

def method_missing clause, *a, &b
  if clause =~ /^([a-z]_by_[a-z_])|(by_[a-z_])/ 
    clause = clause.to_s      
  
    bang = clause =~ /!$/
    clause = clause[0..-2] if bang
  
    finder, field = if clause =~ /^by_/  
      ['first', clause.sub(/by_/, '')]
    else        
      clause.split(/_by_/, 2)          
    end                
    finder = 'first' if finder == 'find'
  
    raise "You can't use bang version with :#{finder}!" if bang and finder != 'first'
  
    raise "invalid arguments for finder (#{a})!" unless a.size == 1
    field_value = a.first

    where(field => field_value).send(finder) || 
      (bang && raise(Mongoid::Errors::DocumentNotFound.new(self, field_value)))
  else
    super
  end
end

Instance Method Details

#find_by_id(id) ⇒ Object Also known as: by_id

find_by_id, special case



34
35
36
# File 'lib/mongoid_misc/simple_finders.rb', line 34

def find_by_id id
  where(_id: id).first
end

#find_by_id!(id) ⇒ Object Also known as: by_id!



39
40
41
# File 'lib/mongoid_misc/simple_finders.rb', line 39

def find_by_id! id
  find_by_id(id) || raise(Mongoid::Errors::DocumentNotFound.new(self, id))
end