public
Description: Natural-looking Finder Queries for ActiveRecord
Homepage: http://www.thoughtbot.com/projects/squirrel
Clone URL: git://github.com/thoughtbot/squirrel.git
A spot of refactoring and a lot of documentation.

git-svn-id: https://svn.thoughtbot.com/plugins/squirrel/trunk@406 
7bbfaf0e-4d1d-0410-9690-a8bb5f8ef2aa
jyurek (author)
Sun Mar 23 21:52:16 -0700 2008
commit  437c20a1609acada75ac4e60aef18bd3a90b0556
tree    e96f4be0c8b4abff59ba49e0a9df54f9459bba3f
parent  5e9f49d3e70d762681fc0b9d98e0418b2b777206
0
...
8
9
10
11
 
12
13
14
15
16
17
18
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
...
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
0
@@ -8,10 +8,47 @@ take a block of Ruby which will get parsed into a nice SQL string
0
 and have its results returned.
0
 
0
 Author:: Jon Yurek (mailto:jyurek@thoughtbot.com)
0
-Copyright:: Copyright(c) 2006 thoughtbot, inc.
0
+Copyright:: Copyright(c) 2008 thoughtbot, inc.
0
 License:: Distributes under the same terms as Ruby
0
 
0
 Squirrel is a plugin for ActiveRecord which attempts to make SQL
0
 querier a much more natural prospect. You can write your queries
0
 in Ruby code and they get translated, including all proper table
0
-joins, into relevant SQL code and executed, returning your results.
0
\ No newline at end of file
0
+joins, into relevant SQL code and executed, returning your results.
0
+
0
+ User.find(:all) do
0
+ first_name.contains? params[:first_name]
0
+ posts.created_at >= 1.week.ago
0
+ end
0
+
0
+This query will return all Users that have a first_name that contains whatever
0
+was passed in as the "first_name" parameter, and that has any Posts that were
0
+created"in the past week. Both columns and associations are referenced as
0
+methods. Columns are referenced exactly as they are in the database, and
0
+associations are referenced exactly as they are specified in their respective
0
+has_many, belongs_to, etc calls. For example, in the snippet above, the User
0
+has_many :posts, and so we use "posts" as the method to refer to that
0
+association.
0
+
0
+This mechanism works for *all* of ActiveRecord's associations, because it
0
+piggybacks on AR's eager loading functionality, which always produces the
0
+joins necessary for getting the columns required.
0
+
0
+By default, all conditions specified in the query are ANDed together. If it is
0
+necessary to have any condition match, you can group your conditions together
0
+using the "any" method, which takes a block containing the conditions.
0
+For example:
0
+
0
+ Playlist.find(:all) do
0
+ any do
0
+ name == "Party Mix"
0
+ total_length > 3600
0
+ end
0
+ end
0
+
0
+... will find all Playlists that either have a name of "Party Mix" or that
0
+have a total length of 1 hour (3600 seconds). There is also an "all" method
0
+that works similarly, but joins with "AND". These groups are nestable."
0
+
0
+Currenly, there is no allowance in Squirrel for either grouping or fetching
0
+columns that aren't part of any of the included tables.
...
1
2
3
 
...
1
 
2
3
0
@@ -1,2 +1,2 @@
0
 require File.dirname(__FILE__) + '/lib/squirrel.rb'
0
-ActiveRecord::Base.send :include, Thoughtbot::Squirrel::ActiveRecordHook
0
\ No newline at end of file
0
+ActiveRecord::Base.send :include, Squirrel::Hook
...
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
 
...
 
 
 
 
 
 
 
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
0
@@ -1,31 +1,32 @@
0
-module Thoughtbot
0
- module Squirrel
0
- class Page
0
- attr_reader :offset, :limit, :page, :per_page
0
- def initialize(offset, limit, page, per_page)
0
- @offset, @limit, @page, @per_page = offset, limit, page, per_page
0
- end
0
+module Squirrel
0
+ # The Page class holds information about the current page of results.
0
+ class Page
0
+ attr_reader :offset, :limit, :page, :per_page
0
+ def initialize(offset, limit, page, per_page)
0
+ @offset, @limit, @page, @per_page = offset, limit, page, per_page
0
     end
0
-
0
- class Paginator < Array
0
- attr_reader :total_results, :per_page, :current, :next, :previous, :first, :last, :current_range
0
- def initialize opts={}
0
- @total_results = opts[:count].to_i
0
- @limit = opts[:limit].to_i
0
- @offset = opts[:offset].to_i
0
-
0
- @per_page = @limit
0
- @current = (@offset / @limit) + 1
0
- @first = 1
0
- @last = ((@total_results-1) / @limit) + 1
0
- @next = @current + 1 if @current < @last
0
- @previous = @current - 1 if @current > 1
0
- @current_range = ((@offset+1)..([@offset+@limit, @total_results].min))
0
-
0
- (@first..@last).each do |page|
0
- self[page-1] = Page.new((page-1) * @per_page, @per_page, page, @per_page)
0
- end
0
+ end
0
+
0
+ # A Paginator object is what gets inserted into the result set and is returned by
0
+ # the #pages method of the result set. Contains offets and limits for all pages.
0
+ class Paginator < Array
0
+ attr_reader :total_results, :per_page, :current, :next, :previous, :first, :last, :current_range
0
+ def initialize opts={}
0
+ @total_results = opts[:count].to_i
0
+ @limit = opts[:limit].to_i
0
+ @offset = opts[:offset].to_i
0
+
0
+ @per_page = @limit
0
+ @current = (@offset / @limit) + 1
0
+ @first = 1
0
+ @last = ((@total_results-1) / @limit) + 1
0
+ @next = @current + 1 if @current < @last
0
+ @previous = @current - 1 if @current > 1
0
+ @current_range = ((@offset+1)..([@offset+@limit, @total_results].min))
0
+
0
+ (@first..@last).each do |page|
0
+ self[page-1] = Page.new((page-1) * @per_page, @per_page, page, @per_page)
0
       end
0
     end
0
   end
0
-end
0
\ No newline at end of file
0
+end
...
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
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
...
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
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
0
@@ -1,323 +1,481 @@
0
 require 'paginator'
0
+require 'extensions'
0
 
0
-module Thoughtbot
0
- module Squirrel
0
- module ActiveRecordHook # :nodoc:
0
- def self.included base
0
- class << base
0
- def find_with_squirrel *args, &blk
0
- args ||= [:all]
0
- if blk || (args.last.is_a?(Hash) && args.last.has_key?(:paginate))
0
- query = Query.new(self, &blk)
0
- query.execute(*args)
0
- else
0
- find_without_squirrel(*args)
0
- end
0
- end
0
- alias_method :find_without_squirrel, :find
0
- alias_method :find, :find_with_squirrel
0
- end
0
- end
0
- end
0
-
0
- class Query
0
- attr_reader :conditions, :model
0
-
0
- def initialize model, &blk
0
- @model = model
0
- @joins = nil
0
- @conditions = ConditionBlock.new(@model, "AND", blk ? blk.binding : nil, :base, &blk)
0
- hand_out_join_associations
0
- end
0
-
0
- def joins
0
- @joins ||= hashized_join_associations
0
- end
0
-
0
- def join_dependency
0
- @join_dependency ||= ::ActiveRecord::Associations::ClassMethods::JoinDependency.new(model, self.include, nil)
0
- end
0
-
0
- def execute *args
0
- if args.first == :query
0
- self
0
- else
0
- opts = args.last.is_a?(Hash) ? args.last : {}
0
- results = []
0
- pagination = opts.delete(:paginate) || {}
0
- model.send(:with_scope, :find => opts) do
0
- @conditions.paginate(pagination) unless pagination.empty?
0
- results = model.find args[0], @conditions.to_params
0
- if @conditions.paginate?
0
- count_conditions = @conditions.to_params
0
- limit = count_conditions.delete(:limit)
0
- offset = count_conditions.delete(:offset)
0
-
0
- class << results
0
- attr_reader :pages
0
- attr_reader :total_results
0
- end
0
-
0
- total_results = model.count(count_conditions)
0
- results.instance_variable_set("@pages", Paginator.new( :count => total_results, :limit => limit, :offset => offset) )
0
- results.instance_variable_set("@total_results", total_results)
0
+# Squirrel is a library for making querying the database using ActiveRecord cleaner, easier
0
+# to read, and less prone to user error. It does this by allowing AR::Base#find to take a block,
0
+# which is run to build the conditions and includes required to execute the query.
0
+module Squirrel
0
+ # When included in AR::Base, it chains the #find method to allow for block execution.
0
+ module Hook
0
+ def self.included base
0
+ class << base
0
+ def find_with_squirrel *args, &blk
0
+ args ||= [:all]
0
+ if blk || (args.last.is_a?(Hash) && args.last.has_key?(:paginate))
0
+ query = Query.new(self, &blk)
0
+ query.execute(*args)
0
+ else
0
+ find_without_squirrel(*args)
0
+ end
0
+ end
0
+ alias_method :find_without_squirrel, :find
0
+ alias_method :find, :find_with_squirrel
0
+ end
0
+ end
0
+ end
0
+
0
+ # The Query is what contains the query and is what handles execution and pagination of the
0
+ # result set.
0
+ class Query
0
+ attr_reader :conditions, :model
0
+
0
+ # Creates a Query specific to the given model (which is a class that descends from AR::Base)
0
+ # and a block that will be run to find the conditions for the #find call.
0
+ def initialize model, &blk
0
+ @model = model
0
+ @joins = nil
0
+ @binding = blk && blk.binding
0
+ @conditions = ConditionGroup.new(@model, "AND", @binding, &blk)
0
+ @conditions.assign_joins( join_dependency )
0
+ end
0
+
0
+ # Builds the dependencies needed to find what AR plans to call the tables in the query
0
+ # by finding and sending what would be passed in as the +include+ parameter to #find.
0
+ # This is a necessary step because what AR calls tables deeply nested might not be
0
+ # completely obvious.)
0
+ def join_dependency
0
+ jd = ::ActiveRecord::Associations::ClassMethods::JoinDependency
0
+ @join_dependency ||= jd.new model,
0
+ @conditions.to_find_include,
0
+ nil
0
+ end
0
+
0
+ # Runs the block which builds the conditions. If requested, paginates the result_set.
0
+ # If the first parameter to #find is :query (instead of :all or :first), then the query
0
+ # object itself is returned. Useful for debugging, but not much else.
0
+ def execute *args
0
+ if args.first == :query
0
+ self
0
+ else
0
+ opts = args.last.is_a?(Hash) ? args.last : {}
0
+ results = []
0
+ pagination = opts.delete(:paginate) || {}
0
+ model.send(:with_scope, :find => opts) do
0
+ @conditions.paginate(pagination) unless pagination.empty?
0
+ find_parameters = { :conditions => to_find_conditions,
0
+ :include => to_find_include,
0
+ :order => to_find_order,
0
+ :limit => to_find_limit,
0
+ :offset => to_find_offset }
0
+ results = model.find args[0], find_parameters
0
+ if @conditions.paginate?
0
+ paginate_result_set results, find_parameters
0
+ end
0
+ end
0
+ results
0
+ end
0
+ end
0
+
0
+ # Delegates the to_find_conditions call to the root ConditionGroup
0
+ def to_find_conditions
0
+ @conditions.to_find_conditions
0
+ end
0
+
0
+ # Delegates the to_find_include call to the root ConditionGroup
0
+ def to_find_include
0
+ @conditions.to_find_include
0
+ end
0
+
0
+ # Delegates the to_find_order call to the root ConditionGroup
0
+ def to_find_order
0
+ @conditions.to_find_order
0
+ end
0
+
0
+ # Delegates the to_find_limit call to the root ConditionGroup
0
+ def to_find_limit
0
+ @conditions.to_find_limit
0
+ end
0
+
0
+ # Delegates the to_find_offset call to the root ConditionGroup
0
+ def to_find_offset
0
+ @conditions.to_find_offset
0
+ end
0
+
0
+ # Used by #execute to paginates the result set if
0
+ # pagination was requested. In this case, it adds +pages+ and +total_results+ accessors
0
+ # to the result set. See Paginator for more details.
0
+ def paginate_result_set set, conditions
0
+ limit = conditions.delete(:limit)
0
+ offset = conditions.delete(:offset)
0
+
0
+ class << set
0
+ attr_reader :pages
0
+ attr_reader :total_results
0
+ end
0
+
0
+ total_results = model.count(conditions)
0
+ set.instance_variable_set("@pages",
0
+ Paginator.new( :count => total_results,
0
+ :limit => limit,
0
+ :offset => offset) )
0
+ set.instance_variable_set("@total_results", total_results)
0
+ end
0
+
0
+ # ConditionGroups are groups of Conditions, oddly enough. They most closely map to models
0
+ # in your schema, but they also handle the grouping jobs for the #any and #all blocks.
0
+ class ConditionGroup
0
+ attr_accessor :model, :logical_join, :binding, :reflection, :path
0
+
0
+ # Creates a ConditionGroup by passing in the following arguments:
0
+ # * model: The AR subclass that defines what columns and associations will be accessible
0
+ # in the given block.
0
+ # * logical_join: A string containing the join that will be used when concatenating the
0
+ # conditions together. The root level ConditionGroup created by Query defaults the
0
+ # join to be "AND", but the #any and #all methods will create specific ConditionGroups
0
+ # using "OR" and "AND" as their join, respectively.
0
+ # * binding: The +binding+ of the block passed to the original #find. Will be used to
0
+ # +eval+ what +self+ would be. This is necessary for using methods like +params+ and
0
+ # +session+ in your controllers.
0
+ # * path: The "path" taken through the models to arrive at this model. For example, if
0
+ # your User class has_many Posts which has_many Comments each of which belongs_to User,
0
+ # the path to the second User would be [:posts, :comments, :user]
0
+ # * reflection: The association used to get to this block. If nil, then no new association
0
+ # was traversed, which means we're in an #any or #all grouping block.
0
+ # * blk: The block to be executed.
0
+ #
0
+ # This method defines a number of methods to be available inside the block, one for each
0
+ # of the columns and associations in the specified model. Note that you CANNOT use
0
+ # user-defined methods on your model inside Squirrel queries. They don't have any meaning
0
+ # in the context of a database query.
0
+ def initialize model, logical_join, binding, path = nil, reflection = nil, &blk
0
+ @model = model
0
+ @logical_join = logical_join
0
+ @conditions = []
0
+ @condition_blocks = []
0
+ @reflection = reflection
0
+ @path = [ path, reflection ].compact.flatten
0
+ @binding = binding
0
+ @order = []
0
+ @negative = false
0
+ @paginator = false
0
+ @block = blk
0
+
0
+ existing_methods = self.class.instance_methods(false)
0
+ (model.column_names - existing_methods).each do |col|
0
+ (class << self; self; end).class_eval do
0
+ define_method(col.to_s.intern) do
0
+ column(col)
0
             end
0
           end
0
- results
0
- end
0
- end
0
-
0
- def include
0
- @conditions.include
0
- end
0
-
0
- protected
0
-
0
- def hand_out_join_associations
0
- @conditions.assign_join_associations(joins)
0
- end
0
-
0
- def join_parent_names assn
0
- if assn.respond_to? :parent
0
- [join_parent_names(assn.parent), assn.reflection.name].flatten
0
- else
0
- [:base]
0
- end
0
- end
0
-
0
- def hashized_join_associations
0
- joins = {}
0
- join_dependency.joins.reverse.each do |join|
0
- join_parent_names(join).inject(joins){|hash, name| hash[name] ||= {} }[:_join] = join
0
- end
0
- joins
0
- end
0
-
0
- class ConditionBlock
0
- attr_accessor :model, :join, :binding, :reflections, :reflection
0
-
0
- def initialize model, join, binding, reflection = nil, &blk
0
- @model = model
0
- @join = join
0
- @conditions = []
0
- @condition_blocks = []
0
- @reflections = []
0
- @reflection = reflection
0
- @binding = binding
0
- @order = []
0
- @negative = false
0
- @paginator = false
0
-
0
- existing_methods = self.class.instance_methods(false)
0
- (model.column_names - existing_methods).each do |col|
0
- (class << self; self; end).class_eval do
0
- define_method(col.to_s.intern) do
0
- column(col)
0
- end
0
- end
0
- end
0
- (model.reflections.keys - existing_methods).each do |assn|
0
- (class << self; self; end).class_eval do
0
- define_method(assn.to_s.intern) do
0
- association(assn)
0
- end
0
- end
0
- end
0
-
0
- if blk
0
- instance_eval &blk
0
- end
0
- end
0
-
0
- def column name
0
- @conditions << Condition.new(name)
0
- @conditions.last
0
- end
0
-
0
- def association name, &blk
0
- name = name.to_s.intern
0
- ref = @model.reflect_on_association(name)
0
- @condition_blocks << ConditionBlock.new(ref.klass, join, binding, ref.name, &blk)
0
- @condition_blocks.last
0
- end
0
-
0
- def any &blk
0
- @condition_blocks << ConditionBlock.new(model, "OR", binding, &blk)
0
- @condition_blocks.last
0
- end
0
-
0
- def all &blk
0
- @condition_blocks << ConditionBlock.new(model, "AND", binding, &blk)
0
- @condition_blocks.last
0
- end
0
-
0
- def order_by *columns
0
- @order += [columns].flatten
0
- end
0
-
0
- def order_clause
0
- @order.blank? ? nil : @order.collect{|col| col.respond_to?(:full_name) ? (col.full_name + (col.negative? ? " DESC" : "")) : col }.join(", ")
0
- end
0
-
0
- def paginate opts = {}
0
- @paginator = true
0
- page = (opts[:page] || 1).to_i
0
- per_page = (opts[:per_page] || 20).to_i
0
- page = 1 if page < 1
0
- limit( per_page, ( page - 1 ) * per_page )
0
- end
0
-
0
- def limit lim, off = nil
0
- find_options.merge! :limit => lim, :offset => (off || find_options[:offset])
0
- end
0
-
0
- def paginate?
0
- @paginator || @condition_blocks.any?(&:paginate?)
0
- end
0
-
0
- def -@
0
- @negative = !@negative
0
- end
0
-
0
- def to_params
0
- ps = {}
0
- ps.merge! :conditions => to_sql, :include => self.include
0
- ps.merge! find_options.merge(:order => order_clause)
0
- ps
0
- end
0
-
0
- def to_sql
0
- segments = conditions.collect{|c| c.to_sql }.compact
0
- return nil if segments.length == 0
0
- cond = "(" + segments.collect{|s| s.first }.join(" #{join} ") + ")"
0
- cond = "NOT #{cond}" if negative?
0
-
0
- values = segments.inject([]){|all, now| all + now[1..-1] }
0
- [ cond, *values ]
0
- end
0
-
0
- def conditions
0
- @conditions + @condition_blocks
0
- end
0
-
0
- def assign_join_associations(joins)
0
- @join_associations = reflection.nil? ? joins : joins[reflection]
0
- conditions.each do |cond|
0
- cond.assign_join_associations(@join_associations)
0
- end
0
- end
0
-
0
- def include
0
- @condition_blocks.inject({}) do |inc, cb|
0
- if cb.reflection.nil?
0
- inc.merge(cb.include)
0
- else
0
- inc[cb.reflection] ||= {}
0
- inc[cb.reflection] = inc[cb.reflection].merge(cb.include)
0
- inc
0
- end
0
- end
0
- end
0
-
0
- def complex?
0
- @condition_blocks.any?{|each| each.reflection != self.reflection }
0
- end
0
-
0
- def negative?
0
- @negative
0
- end
0
-
0
- def method_missing meth, *args
0
- m = eval("method(:#{meth})", binding)
0
- if m
0
- m.call(*args)
0
- else
0
- raise NameError, "Column or Relationship #{meth} not defined for #{@model.class.name}"
0
- end
0
- end
0
-
0
- def find_options
0
- @find_options ||= {}
0
- end
0
- end
0
-
0
- class Condition
0
- attr_reader :name, :operator, :operand
0
-
0
- def initialize name
0
- @name = name
0
- @sql = nil
0
- @negative = false
0
- end
0
-
0
- [ :==, :===, :=~, :<=>, :<=, :<, :>, :>= ].each do |op|
0
- define_method(op) do |val|
0
- @operator = op
0
- @operand = val
0
- self
0
- end
0
- end
0
-
0
- def contains? val
0
- @operator = :contains
0
- @operand = val
0
- self
0
         end
0
+ (model.reflections.keys - existing_methods).each do |assn|
0
+ (class << self; self; end).class_eval do
0
+ define_method(assn.to_s.intern) do
0
+ association(assn)
0
+ end
0
+ end
0
+ end
0
+
0
+ execute_block
0
+ end
0
+
0
+ # Creates a Condition and queues it for inclusion. When calling a method defined
0
+ # during the creation of the ConditionGroup object is the same as calling column(:column_name).
0
+ # This is useful if you need to access a column that happens to coincide with the name of
0
+ # an already-defined method (e.g. anything returned by instance_methods(false) for the
0
+ # given model).
0
+ def column name
0
+ @conditions << Condition.new(name)
0
+ @conditions.last
0
+ end
0
+
0
+ # Similar to #column, this will create an association even if you can't use the normal
0
+ # method version.
0
+ def association name, &blk
0
+ name = name.to_s.intern
0
+ ref = @model.reflect_on_association(name)
0
+ @condition_blocks << ConditionGroup.new(ref.klass, logical_join, binding, path, ref.name, &blk)
0
+ @condition_blocks.last
0
+ end
0
+
0
+ # Creates a ConditionGroup that has the logical_join set to "OR".
0
+ def any &blk
0
+ @condition_blocks << ConditionGroup.new(model, "OR", binding, path, &blk)
0
+ @condition_blocks.last
0
+ end
0
+
0
+ # Creates a ConditionGroup that has the logical_join set to "AND".
0
+ def all &blk
0
+ @condition_blocks << ConditionGroup.new(model, "AND", binding, path, &blk)
0
+ @condition_blocks.last
0
+ end
0
+
0
+ # Sets the arguments for the :order parameter. Arguments can be columns (i.e. Conditions)
0
+ # or they can be strings (for "RANDOM()", etc.). If a Condition is used, and the column is
0
+ # negated using #not or #desc, then the resulting specification in the ORDER clause will
0
+ # be ordered descending. That is, "order_by name.desc" will become "ORDER name DESC"
0
+ def order_by *columns
0
+ @order += [columns].flatten
0
+ end
0
+
0
+ # Flags the result set to be paginated according to the :page and :per_page parameters
0
+ # to this method.
0
+ def paginate opts = {}
0
+ @paginator = true
0
+ page = (opts[:page] || 1).to_i
0
+ per_page = (opts[:per_page] || 20).to_i
0
+ page = 1 if page < 1
0
+ limit( per_page, ( page - 1 ) * per_page )
0
+ end
0
+
0
+ # Similar to #paginate, but does not flag the result set for pagination. Takes a limit
0
+ # and an offset (by default the offset is 0).