blob: dfb8a3ba6033d2e90d0b5d758a9e0729166bad24 (
plain) (
blame)
1
2
3
4
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
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
|
module ActiveRecord
# = Active Record Dynamic Finder Match
#
# Provides dynamic attribute-based finders such as <tt>find_by_country</tt>
# if, for example, the <tt>Person</tt> has an attribute with that name.
class DynamicFinderMatch
def self.match(method)
df_match = self.new(method)
df_match.finder ? df_match : nil
end
def initialize(method)
@finder = :first
@bang = false
@instantiator = nil
case method.to_s
when /^find_(all_by|last_by|by)_([_a-zA-Z]\w*)$/
@finder = :last if $1 == 'last_by'
@finder = :all if $1 == 'all_by'
names = $2
when /^find_by_([_a-zA-Z]\w*)\!$/
@bang = true
names = $1
when /^find_or_(initialize|create)_by_([_a-zA-Z]\w*)$/
@instantiator = $1 == 'initialize' ? :new : :create
names = $2
else
@finder = nil
end
@attribute_names = names && names.split('_and_')
end
attr_reader :finder, :attribute_names, :instantiator
def finder?
!@finder.nil? && @instantiator.nil?
end
def instantiator?
@finder == :first && !@instantiator.nil?
end
def creator?
@finder == :first && @instantiator == :create
end
def bang?
@bang
end
end
end
|