Class: Mongoid::DynamicFinder

Inherits:
Object
  • Object
show all
Defined in:
lib/mongoid/dynamic_finder.rb

Constant Summary collapse

FINDER =

Regex for standard dynamic finder methods.

/^find_(all_by|last_by|by)_([_a-zA-Z]\w*)$/
CREATOR =

Regex for finder methods that create objects if nothing found.

/^find_or_(initialize|create)_by_([_a-zA-Z]\w*)$/

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(method, *args) ⇒ DynamicFinder

Creates a new DynamicFinder given the supplied method name. This parses the name and sets up the appropriate finder type and attribute names in order to perform the search.

Options:

method: The name of the dynamic finder method.

Example:

DynamicFinder.new(:find_by_title_and_age)



22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
# File 'lib/mongoid/dynamic_finder.rb', line 22

def initialize(method, *args)
  @finder, @args = :first, args
  case method.to_s
  when FINDER
    @finder = :all if $1 == "all_by"
    @finder = :last if $1 == "last_by"
    names = $2
  when CREATOR then
    @creator = ($1 == "initialize") ? :instantiate : :create
    names = $2
  else
    @finder = nil
  end
  @attributes = names && names.split("_and_")
  generate_conditions
end

Instance Attribute Details

#conditionsObject (readonly)

Returns the value of attribute conditions.



9
10
11
# File 'lib/mongoid/dynamic_finder.rb', line 9

def conditions
  @conditions
end

#finderObject (readonly)

Returns the value of attribute finder.



9
10
11
# File 'lib/mongoid/dynamic_finder.rb', line 9

def finder
  @finder
end

Instance Method Details

#create(klass) ⇒ Object

Will create a new Document based on the type of creator keyword in the method, given the supplied class.

Options:

klass: The Document class to be instantiated.

Example:

finder.create(Person)



49
50
51
# File 'lib/mongoid/dynamic_finder.rb', line 49

def create(klass)
  klass.send(@creator, @conditions) if @creator
end