aboutsummaryrefslogtreecommitdiffstats
path: root/activerecord/lib/active_record/dynamic_finder_match.rb
blob: 2b4f1bbf92832ce19fe4a6cc9ca5827a405f0b51 (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
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
module ActiveRecord

  # = Active Record Dynamic Finder Match
  #
  # Refer to ActiveRecord::Base documentation for Dynamic attribute-based finders for detailed info
  #
  class DynamicFinderMatch
    def self.match(method)
      [ FindBy, FindByBang, FindOrInitializeCreateBy ].each do |klass|
        o = klass.match(method.to_s)
        return o if o
      end
      nil
    end

    def initialize(finder, names, instantiator = nil)
      @finder          = finder
      @instantiator    = instantiator
      @attribute_names = names.split('_and_')
    end

    attr_reader :finder, :attribute_names, :instantiator

    def finder?
      @finder && !@instantiator
    end

    def creator?
      @finder == :first && @instantiator == :create
    end

    def instantiator?
      @instantiator
    end

    def bang?
      false
    end

    def valid_arguments?(arguments)
      arguments.size >= @attribute_names.size
    end
  end

  class FindBy < DynamicFinderMatch
    def self.match(method)
      if method =~ /^find_(all_|last_)?by_([_a-zA-Z]\w*)$/
        new($1 == 'last_' ? :last : $1 == 'all_' ? :all : :first, $2)
      end
    end
  end

  class FindByBang < DynamicFinderMatch
    def self.match(method)
      if method =~ /^find_by_([_a-zA-Z]\w*)\!$/
        new(:first, $1)
      end
    end

    def bang?
      true
    end
  end

  class FindOrInitializeCreateBy < DynamicFinderMatch
    def self.match(method)
      instantiator = nil
      if method =~ /^find_or_(initialize|create)_by_([_a-zA-Z]\w*)$/
        new(:first, $2, $1 == 'initialize' ? :new : :create)
      end
    end

    def valid_arguments?(arguments)
      arguments.size == 1 && arguments.first.is_a?(Hash) || super
    end
  end
end