-
Notifications
You must be signed in to change notification settings - Fork 48
/
query.rb
65 lines (52 loc) · 1.06 KB
/
query.rb
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
module Rectify
module SqlQuery
def query
model.find_by_sql([sql, params])
end
end
class Query
def initialize(scope = ActiveRecord::NullRelation)
@scope = scope
end
def query
@scope
end
def |(other)
if relation? && other.relation?
Rectify::Query.new(cached_query.merge(other.cached_query))
elsif eager? && other.eager?
Rectify::Query.new(cached_query | other.cached_query)
else
fail UnableToComposeQueries.new(self, other)
end
end
def count
cached_query.count
end
def first
cached_query.first
end
def each(&block)
cached_query.each(&block)
end
def exists?
return cached_query.exists? if relation?
cached_query.present?
end
def none?
!exists?
end
def to_a
cached_query.to_a
end
def relation?
cached_query.is_a?(ActiveRecord::Relation)
end
def eager?
cached_query.is_a?(Array)
end
def cached_query
@cached_query ||= query
end
end
end