/
automatic_scopes.rb
375 lines (286 loc) · 11.9 KB
/
automatic_scopes.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
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
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
module Hobo
module Scopes
module AutomaticScopes
def create_automatic_scope(name)
ScopeBuilder.new(self, name).create_scope
rescue ActiveRecord::StatementInvalid => e
# Problem with the database? Don't try to create automatic
# scopes
if ActiveRecord::Base.logger
ActiveRecord::Base.logger.warn "!! Database exception during hobo auto-scope creation -- continuing automatic scopes"
ActiveRecord::Base.logger.warn "!! #{e.to_s}"
end
false
end
end
# The methods on this module add scopes to the given class
class ScopeBuilder
def initialize(klass, name)
@klass = klass
@name = name.to_s
end
attr_reader :name
def create_scope
matched_scope = true
# --- Association Queries --- #
# with_players(player1, player2)
if name =~ /^with_(.*)/ && (refl = reflection($1))
def_scope do |*records|
if records.empty?
{ :conditions => exists_sql_condition(refl, true) }
else
records = records.flatten.compact.map {|r| find_if_named(refl, r) }
exists_sql = ([exists_sql_condition(refl)] * records.length).join(" AND ")
{ :conditions => [exists_sql] + records }
end
end
# with_player(a_player)
elsif name =~ /^with_(.*)/ && (refl = reflection($1.pluralize))
exists_sql = exists_sql_condition(refl)
def_scope do |record|
record = find_if_named(refl, record)
{ :conditions => [exists_sql, record] }
end
# without_players(player1, player2)
elsif name =~ /^without_(.*)/ && (refl = reflection($1))
def_scope do |*records|
if records.empty?
{ :conditions => "NOT (#{exists_sql_condition(refl, true)})" }
else
records = records.flatten.compact.map {|r| find_if_named(refl, r) }
exists_sql = ([exists_sql_condition(refl)] * records.length).join(" AND ")
{ :conditions => ["NOT (#{exists_sql})"] + records }
end
end
# without_player(a_player)
elsif name =~ /^without_(.*)/ && (refl = reflection($1.pluralize))
exists_sql = exists_sql_condition(refl)
def_scope do |record|
record = find_if_named(refl, record)
{ :conditions => ["NOT #{exists_sql}", record] }
end
# team_is(a_team)
elsif name =~ /^(.*)_is$/ && (refl = reflection($1)) && refl.macro.in?([:has_one, :belongs_to])
if refl.options[:polymorphic]
def_scope do |record|
record = find_if_named(refl, record)
{ :conditions => ["#{foreign_key_column refl} = ? AND #{$1}_type = ?", record, record.class.name] }
end
else
def_scope do |record|
record = find_if_named(refl, record)
{ :conditions => ["#{foreign_key_column refl} = ?", record] }
end
end
# team_is_not(a_team)
elsif name =~ /^(.*)_is_not$/ && (refl = reflection($1)) && refl.macro.in?([:has_one, :belongs_to])
if refl.options[:polymorphic]
def_scope do |record|
record = find_if_named(refl, record)
{ :conditions => ["#{foreign_key_column refl} <> ? OR #{name}_type <> ?", record, record.class.name] }
end
else
def_scope do |record|
record = find_if_named(refl, record)
{ :conditions => ["#{foreign_key_column refl} <> ?", record] }
end
end
# --- Column Queries --- #
# name_is(str)
elsif name =~ /^(.*)_is$/ && (col = column($1))
def_scope do |str|
{ :conditions => ["#{column_sql(col)} = ?", str] }
end
# name_is_not(str)
elsif name =~ /^(.*)_is_not$/ && (col = column($1))
def_scope do |str|
{ :conditions => ["#{column_sql(col)} <> ?", str] }
end
# name_contains(str)
elsif name =~ /^(.*)_contains$/ && (col = column($1))
def_scope do |str|
{ :conditions => ["#{column_sql(col)} LIKE ?", "%#{str}%"] }
end
# name_does_not_contain
elsif name =~ /^(.*)_does_not_contain$/ && (col = column($1))
def_scope do |str|
{ :conditions => ["#{column_sql(col)} NOT LIKE ?", "%#{str}%"] }
end
# name_starts(str)
elsif name =~ /^(.*)_starts$/ && (col = column($1))
def_scope do |str|
{ :conditions => ["#{column_sql(col)} LIKE ?", "#{str}%"] }
end
# name_does_not_start
elsif name =~ /^(.*)_does_not_start$/ && (col = column($1))
def_scope do |str|
{ :conditions => ["#{column_sql(col)} NOT LIKE ?", "#{str}%"] }
end
# name_ends(str)
elsif name =~ /^(.*)_ends$/ && (col = column($1))
def_scope do |str|
{ :conditions => ["#{column_sql(col)} LIKE ?", "%#{str}"] }
end
# name_does_not_end(str)
elsif name =~ /^(.*)_does_not_end$/ && (col = column($1))
def_scope do |str|
{ :conditions => ["#{column_sql(col)} NOT LIKE ?", "%#{str}"] }
end
# published (a boolean column)
elsif (col = column(name)) && (col.type == :boolean)
def_scope :conditions => ["#{column_sql(col)} = ?", true]
# not_published
elsif name =~ /^not_(.*)$/ && (col = column($1)) && (col.type == :boolean)
def_scope :conditions => ["#{column_sql(col)} <> ?", true]
# published_before(time)
elsif name =~ /^(.*)_before$/ && (col = column("#{$1}_at") || column("#{$1}_date") || column("#{$1}_on")) && col.type.in?([:date, :datetime, :time, :timestamp])
def_scope do |time|
{ :conditions => ["#{column_sql(col)} < ?", time] }
end
# published_after(time)
elsif name =~ /^(.*)_after$/ && (col = column("#{$1}_at") || column("#{$1}_date") || column("#{$1}_on")) && col.type.in?([:date, :datetime, :time, :timestamp])
def_scope do |time|
{ :conditions => ["#{column_sql(col)} > ?", time] }
end
# published_between(time1, time2)
elsif name =~ /^(.*)_between$/ && (col = column("#{$1}_at") || column("#{$1}_date") || column("#{$1}_on")) && col.type.in?([:date, :datetime, :time, :timestamp])
def_scope do |time1, time2|
{ :conditions => ["#{column_sql(col)} >= ? AND #{column_sql(col)} <= ?", time1, time2] }
end
# active (a lifecycle state)
elsif @klass.has_lifecycle? && name.to_sym.in?(@klass::Lifecycle.state_names)
if @klass::Lifecycle.state_names.length == 1
# nothing to check for - create a dummy scope
def_scope :conditions => ""
true
else
def_scope :conditions => ["#{@klass.table_name}.#{@klass::Lifecycle.state_field} = ?", name]
end
# self is / is not
elsif name == "is"
def_scope do |record|
{ :conditions => ["#{@klass.table_name}.#{@klass.primary_key} = ?", record] }
end
elsif name == "is_not"
def_scope do |record|
{ :conditions => ["#{@klass.table_name}.#{@klass.primary_key} <> ?", record] }
end
else
case name
when "by_most_recent"
def_scope :order => "#{@klass.table_name}.created_at DESC"
when "recent"
if "created_at".in?(@klass.columns.*.name)
def_scope do |*args|
count = args.first || 6
{ :limit => count, :order => "#{@klass.table_name}.created_at DESC" }
end
else
def_scope do |*args|
count = args.first || 6
{ :limit => count }
end
end
when "limit"
def_scope do |count|
{ :limit => count }
end
when "order_by"
klass = @klass
def_scope do |*args|
field, asc = args
type = klass.attr_type(field)
if type.nil? #a virtual attribute from an SQL alias, e.g., 'total' from 'COUNT(*) AS total'
colspec = "#{field}" # don't prepend the table name
elsif type.respond_to?(:table_name) && (name = type.name_attribute)
include = field
colspec = "#{type.table_name}.#{name}"
else
colspec = "#{klass.table_name}.#{field}"
end
{ :order => "#{colspec} #{asc._?.upcase}", :include => include }
end
when "include"
def_scope do |inclusions|
{ :include => inclusions }
end
when "search"
def_scope do |query, *fields|
words = query.split
args = []
word_queries = words.map do |word|
field_query = '(' + fields.map { |field| "(#{@klass.table_name+'.' unless field.to_s.index('.')}#{field} like ?)" }.join(" OR ") + ')'
args += ["%#{word}%"] * fields.length
field_query
end
{ :conditions => [word_queries.join(" AND ")] + args }
end
else
matched_scope = false
end
end
matched_scope
end
def column_sql(column)
"#{@klass.table_name}.#{column.name}"
end
def exists_sql_condition(reflection, any=false)
owner = @klass
owner_primary_key = "#{owner.table_name}.#{owner.primary_key}"
if reflection.options[:through]
join_table = reflection.through_reflection.klass.table_name
owner_fkey = reflection.through_reflection.primary_key_name
if any
"EXISTS (SELECT * FROM #{join_table} WHERE #{join_table}.#{owner_fkey} = #{owner_primary_key})"
else
source_fkey = reflection.source_reflection.primary_key_name
"EXISTS (SELECT * FROM #{join_table} " +
"WHERE #{join_table}.#{source_fkey} = ? AND #{join_table}.#{owner_fkey} = #{owner_primary_key})"
end
else
foreign_key = reflection.primary_key_name
related = reflection.klass
if any
"EXISTS (SELECT * FROM #{related.table_name} " +
"WHERE #{related.table_name}.#{foreign_key} = #{owner_primary_key})"
else
"EXISTS (SELECT * FROM #{related.table_name} " +
"WHERE #{related.table_name}.#{foreign_key} = #{owner_primary_key} AND " +
"#{related.table_name}.#{related.primary_key} = ?)"
end
end
end
def find_if_named(reflection, string_or_record)
if string_or_record.is_a?(String)
name = string_or_record
reflection.klass.named(name)
else
string_or_record # a record
end
end
def column(name)
@klass.column(name)
end
def reflection(name)
@klass.reflections[name.to_sym]
end
def def_scope(options={}, &block)
_name = name.to_sym
@klass.named_scope(_name, block || options)
# this is tricky; ordinarily, we'd worry about subclasses that haven't yet been loaded.
# HOWEVER, they will pick up the scope setting via read_inheritable_attribute when they do
# load, so only the currently existing subclasses need to be fixed up.
_scope = @klass.scopes[_name]
@klass.send(:subclasses).each do |k|
k.scopes[_name] = _scope
end
end
def primary_key_column(refl)
"#{refl.klass.table_name}.#{refl.klass.primary_key}"
end
def foreign_key_column(refl)
"#{@klass.table_name}.#{refl.primary_key_name}"
end
end
end
end