Module: OverrideActiveRecordDynamicFinders::ClassMethods

Defined in:
lib/override_active_record_dynamic_finders/class_methods.rb

Constant Summary collapse

KEYS_SET =
[:joins, :select, :group, :order, :having, :limit, :offset, :conditions, :extend, :include]
ALL =
:all

Instance Method Summary collapse

Dynamic Method Handling

This class handles dynamic methods through the method_missing method

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



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
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
# File 'lib/override_active_record_dynamic_finders/class_methods.rb', line 51

def method_missing(method_id, *args, &block)
  method = method_id.to_s

  if method.start_with?("find_")

    case method
    when /^find_(all_|last_)?by_([_a-zA-Z]\w*)$/
      finder  = :last if $1 == 'last_'
      finder  = :all if $1 == 'all_'
      names   = $2.split("_and_")
    when /^find_by_([_a-zA-Z]\w*)$/
      names   = $1.split("_and_")
    end

    finder      ||= :first
    finder_hash = {}
    finder_hash = args.delete(args.last) if args.last.is_a?(Hash)

    raise "Invalid number of arguments", ArgumentError if args.size != names.size

    conditions = nil

    if finder_hash[:conditions].blank? || finder_hash[:conditions].is_a?(Hash)
      conditions = {}

      names.each_with_index do |name, index|
        conditions[name.to_sym] = args[index]
      end

      finder_hash[:conditions] = {} if finder_hash[:conditions].blank?
      finder_hash[:conditions].merge!(conditions)

    else
      conditions = []

      names.each_with_index do |name, index|
        conditions << " #{name} = '#{args[index]}' "
      end

      conditions = conditions.join(" AND ")

      if finder_hash[:conditions].is_a?(Array)
        finder_hash[:conditions][0] += " AND " + conditions
      else
        finder_hash[:conditions] += " AND " + conditions
      end
    end

    find(finder, finder_hash)

  else
    super method_id, *args, &block
  end
end

Instance Method Details

#count(*args) ⇒ Object



18
19
20
21
22
23
24
25
26
27
28
29
# File 'lib/override_active_record_dynamic_finders/class_methods.rb', line 18

def count(*args)

  if args.last.is_a?(Hash) && ALL == args.first
    compute_result(*args).count
  elsif args.last.is_a?(Hash) && ALL != args.first
    compute_result(*args).count(args.first)
  elsif args.first.is_a?(Symbol) && ALL == args.first
    count
  else
    super *args
  end
end

#find(*args) ⇒ Object



7
8
9
10
11
12
13
14
15
16
# File 'lib/override_active_record_dynamic_finders/class_methods.rb', line 7

def find(*args)
  if args.first.is_a?(Symbol) && args.last.is_a?(Hash)
    compute_result(*args).send(args.first)
  elsif args.first.is_a?(Symbol) && !args.last.is_a?(Hash)
    result = self
    result.send(args.first)
  else
    super *args
  end
end