larsklevan-will_paginate 2.3.12

Sign up to get free protection for your applications and to get access to all the features.
@@ -0,0 +1,43 @@
1
+ require 'set'
2
+ require 'will_paginate/array'
3
+
4
+ # helper to check for method existance in ruby 1.8- and 1.9-compatible way
5
+ # because `methods`, `instance_methods` and others return strings in 1.8 and symbols in 1.9
6
+ #
7
+ # ['foo', 'bar'].include_method?(:foo) # => true
8
+ class Array
9
+ def include_method?(name)
10
+ name = name.to_sym
11
+ !!(find { |item| item.to_sym == name })
12
+ end
13
+ end
14
+
15
+ unless Hash.instance_methods.include_method? :except
16
+ Hash.class_eval do
17
+ # Returns a new hash without the given keys.
18
+ def except(*keys)
19
+ rejected = Set.new(respond_to?(:convert_key) ? keys.map { |key| convert_key(key) } : keys)
20
+ reject { |key,| rejected.include?(key) }
21
+ end
22
+
23
+ # Replaces the hash without only the given keys.
24
+ def except!(*keys)
25
+ replace(except(*keys))
26
+ end
27
+ end
28
+ end
29
+
30
+ unless Hash.instance_methods.include_method? :slice
31
+ Hash.class_eval do
32
+ # Returns a new hash with only the given keys.
33
+ def slice(*keys)
34
+ allowed = Set.new(respond_to?(:convert_key) ? keys.map { |key| convert_key(key) } : keys)
35
+ reject { |key,| !allowed.include?(key) }
36
+ end
37
+
38
+ # Replaces the hash with only the given keys.
39
+ def slice!(*keys)
40
+ replace(slice(*keys))
41
+ end
42
+ end
43
+ end
@@ -0,0 +1,265 @@
1
+ require 'will_paginate/core_ext'
2
+
3
+ module WillPaginate
4
+ # A mixin for ActiveRecord::Base. Provides +per_page+ class method
5
+ # and hooks things up to provide paginating finders.
6
+ #
7
+ # Find out more in WillPaginate::Finder::ClassMethods
8
+ #
9
+ module Finder
10
+ def self.included(base)
11
+ base.extend ClassMethods
12
+ class << base
13
+ alias_method_chain :method_missing, :paginate
14
+ # alias_method_chain :find_every, :paginate
15
+ end
16
+ base.class_inheritable_accessor :per_page
17
+ base.class_inheritable_accessor :max_per_page
18
+ base.write_inheritable_attribute :per_page, 30
19
+ base.write_inheritable_attribute :max_per_page, 1000
20
+ end
21
+
22
+ # = Paginating finders for ActiveRecord models
23
+ #
24
+ # WillPaginate adds +paginate+, +per_page+ and other methods to
25
+ # ActiveRecord::Base class methods and associations. It also hooks into
26
+ # +method_missing+ to intercept pagination calls to dynamic finders such as
27
+ # +paginate_by_user_id+ and translate them to ordinary finders
28
+ # (+find_all_by_user_id+ in this case).
29
+ #
30
+ # In short, paginating finders are equivalent to ActiveRecord finders; the
31
+ # only difference is that we start with "paginate" instead of "find" and
32
+ # that <tt>:page</tt> is required parameter:
33
+ #
34
+ # @posts = Post.paginate :all, :page => params[:page], :order => 'created_at DESC'
35
+ #
36
+ # In paginating finders, "all" is implicit. There is no sense in paginating
37
+ # a single record, right? So, you can drop the <tt>:all</tt> argument:
38
+ #
39
+ # Post.paginate(...) => Post.find :all
40
+ # Post.paginate_all_by_something => Post.find_all_by_something
41
+ # Post.paginate_by_something => Post.find_all_by_something
42
+ #
43
+ # == The importance of the <tt>:order</tt> parameter
44
+ #
45
+ # In ActiveRecord finders, <tt>:order</tt> parameter specifies columns for
46
+ # the <tt>ORDER BY</tt> clause in SQL. It is important to have it, since
47
+ # pagination only makes sense with ordered sets. Without the <tt>ORDER
48
+ # BY</tt> clause, databases aren't required to do consistent ordering when
49
+ # performing <tt>SELECT</tt> queries; this is especially true for
50
+ # PostgreSQL.
51
+ #
52
+ # Therefore, make sure you are doing ordering on a column that makes the
53
+ # most sense in the current context. Make that obvious to the user, also.
54
+ # For perfomance reasons you will also want to add an index to that column.
55
+ module ClassMethods
56
+ # This is the main paginating finder.
57
+ #
58
+ # == Special parameters for paginating finders
59
+ # * <tt>:page</tt> -- REQUIRED, but defaults to 1 if false or nil
60
+ # * <tt>:per_page</tt> -- defaults to <tt>CurrentModel.per_page</tt> (which is 30 if not overridden)
61
+ # * <tt>:total_entries</tt> -- use only if you manually count total entries
62
+ # * <tt>:count</tt> -- additional options that are passed on to +count+
63
+ # * <tt>:finder</tt> -- name of the ActiveRecord finder used (default: "find")
64
+ #
65
+ # All other options (+conditions+, +order+, ...) are forwarded to +find+
66
+ # and +count+ calls.
67
+ def paginate(*args)
68
+ options = args.pop || {}
69
+ page, per_page, total_entries = wp_parse_options(options)
70
+ finder = (options[:finder] || 'find').to_s
71
+
72
+ if finder == 'find'
73
+ # an array of IDs may have been given:
74
+ total_entries ||= (Array === args.first and args.first.size)
75
+ # :all is implicit
76
+ args.unshift(:all) if args.empty?
77
+ end
78
+
79
+ WillPaginate::Collection.create(page, per_page, total_entries) do |pager|
80
+ count_options = options.except :page, :per_page, :total_entries, :finder
81
+ find_options = count_options.except(:count).update(:offset => pager.offset, :limit => pager.per_page)
82
+
83
+ args << find_options
84
+ # @options_from_last_find = nil
85
+ pager.replace(send(finder, *args) { |*a| yield(*a) if block_given? })
86
+
87
+ # magic counting for user convenience:
88
+ pager.total_entries = wp_count(count_options, args, finder) unless pager.total_entries
89
+ end
90
+ end
91
+
92
+ # Iterates through all records by loading one page at a time. This is useful
93
+ # for migrations or any other use case where you don't want to load all the
94
+ # records in memory at once.
95
+ #
96
+ # It uses +paginate+ internally; therefore it accepts all of its options.
97
+ # You can specify a starting page with <tt>:page</tt> (default is 1). Default
98
+ # <tt>:order</tt> is <tt>"id"</tt>, override if necessary.
99
+ #
100
+ # See {Faking Cursors in ActiveRecord}[http://weblog.jamisbuck.org/2007/4/6/faking-cursors-in-activerecord]
101
+ # where Jamis Buck describes this and a more efficient way for MySQL.
102
+ def paginated_each(options = {})
103
+ options = { :order => 'id', :page => 1 }.merge options
104
+ options[:page] = options[:page].to_i
105
+ options[:total_entries] = 0 # skip the individual count queries
106
+ total = 0
107
+
108
+ begin
109
+ collection = paginate(options)
110
+ with_exclusive_scope(:find => {}) do
111
+ # using exclusive scope so that the block is yielded in scope-free context
112
+ total += collection.each { |item| yield item }.size
113
+ end
114
+ options[:page] += 1
115
+ end until collection.size < collection.per_page
116
+
117
+ total
118
+ end
119
+
120
+ # Wraps +find_by_sql+ by simply adding LIMIT and OFFSET to your SQL string
121
+ # based on the params otherwise used by paginating finds: +page+ and
122
+ # +per_page+.
123
+ #
124
+ # Example:
125
+ #
126
+ # @developers = Developer.paginate_by_sql ['select * from developers where salary > ?', 80000],
127
+ # :page => params[:page], :per_page => 3
128
+ #
129
+ # A query for counting rows will automatically be generated if you don't
130
+ # supply <tt>:total_entries</tt>. If you experience problems with this
131
+ # generated SQL, you might want to perform the count manually in your
132
+ # application.
133
+ #
134
+ def paginate_by_sql(sql, options)
135
+ WillPaginate::Collection.create(*wp_parse_options(options)) do |pager|
136
+ query = sanitize_sql(sql.dup)
137
+ original_query = query.dup
138
+ # add limit, offset
139
+ add_limit! query, :offset => pager.offset, :limit => pager.per_page
140
+ # perfom the find
141
+ pager.replace find_by_sql(query)
142
+
143
+ unless pager.total_entries
144
+ count_query = original_query.sub /\bORDER\s+BY\s+[\w`,\s]+$/mi, ''
145
+ count_query = "SELECT COUNT(*) FROM (#{count_query})"
146
+
147
+ unless self.connection.adapter_name =~ /^(oracle|oci$)/i
148
+ count_query << ' AS count_table'
149
+ end
150
+ # perform the count query
151
+ pager.total_entries = count_by_sql(count_query)
152
+ end
153
+ end
154
+ end
155
+
156
+ def respond_to?(method, include_priv = false) #:nodoc:
157
+ case method.to_sym
158
+ when :paginate, :paginate_by_sql
159
+ true
160
+ else
161
+ super(method.to_s.sub(/^paginate/, 'find'), include_priv)
162
+ end
163
+ end
164
+
165
+ protected
166
+
167
+ def method_missing_with_paginate(method, *args) #:nodoc:
168
+ # did somebody tried to paginate? if not, let them be
169
+ unless method.to_s.index('paginate') == 0
170
+ if block_given?
171
+ return method_missing_without_paginate(method, *args) { |*a| yield(*a) }
172
+ else
173
+ return method_missing_without_paginate(method, *args)
174
+ end
175
+ end
176
+
177
+ # paginate finders are really just find_* with limit and offset
178
+ finder = method.to_s.sub('paginate', 'find')
179
+ finder.sub!('find', 'find_all') if finder.index('find_by_') == 0
180
+
181
+ options = args.pop
182
+ raise ArgumentError, 'parameter hash expected' unless options.respond_to? :symbolize_keys
183
+ options = options.dup
184
+ options[:finder] = finder
185
+ args << options
186
+
187
+ paginate(*args) { |*a| yield(*a) if block_given? }
188
+ end
189
+
190
+ # Does the not-so-trivial job of finding out the total number of entries
191
+ # in the database. It relies on the ActiveRecord +count+ method.
192
+ def wp_count(options, args, finder)
193
+ excludees = [:count, :order, :limit, :offset, :readonly]
194
+ excludees << :from unless ActiveRecord::Calculations::CALCULATIONS_OPTIONS.include?(:from)
195
+
196
+ # we may be in a model or an association proxy
197
+ klass = (@owner and @reflection) ? @reflection.klass : self
198
+
199
+ # Use :select from scope if it isn't already present.
200
+ options[:select] = scope(:find, :select) unless options[:select]
201
+
202
+ if options[:select] and options[:select] =~ /^\s*DISTINCT\b/i
203
+ # Remove quoting and check for table_name.*-like statement.
204
+ if options[:select].gsub('`', '') =~ /\w+\.\*/
205
+ options[:select] = "DISTINCT #{klass.table_name}.#{klass.primary_key}"
206
+ end
207
+ else
208
+ excludees << :select # only exclude the select param if it doesn't begin with DISTINCT
209
+ end
210
+
211
+ # count expects (almost) the same options as find
212
+ count_options = options.except *excludees
213
+
214
+ # merge the hash found in :count
215
+ # this allows you to specify :select, :order, or anything else just for the count query
216
+ count_options.update options[:count] if options[:count]
217
+
218
+ # forget about includes if they are irrelevant (Rails 2.1)
219
+ if count_options[:include] and
220
+ klass.private_methods.include_method?(:references_eager_loaded_tables?) and
221
+ !klass.send(:references_eager_loaded_tables?, count_options)
222
+ count_options.delete :include
223
+ end
224
+
225
+ # we may have to scope ...
226
+ counter = Proc.new { count(count_options) }
227
+
228
+ count = if finder.index('find_') == 0 and klass.respond_to?(scoper = finder.sub('find', 'with'))
229
+ # scope_out adds a 'with_finder' method which acts like with_scope, if it's present
230
+ # then execute the count with the scoping provided by the with_finder
231
+ send(scoper, &counter)
232
+ elsif finder =~ /^find_(all_by|by)_([_a-zA-Z]\w*)$/
233
+ # extract conditions from calls like "paginate_by_foo_and_bar"
234
+ attribute_names = $2.split('_and_')
235
+ conditions = construct_attributes_from_arguments(attribute_names, args)
236
+ with_scope(:find => { :conditions => conditions }, &counter)
237
+ else
238
+ counter.call
239
+ end
240
+
241
+ count.respond_to?(:length) ? count.length : count
242
+ end
243
+
244
+ def wp_parse_options(options) #:nodoc:
245
+ options = options.symbolize_keys
246
+
247
+ if options[:count] and options[:total_entries]
248
+ raise ArgumentError, ':count and :total_entries are mutually exclusive'
249
+ end
250
+
251
+ page = options[:page] || 1
252
+ per_page = [(options[:per_page] || self.per_page).to_i, self.max_per_page].min
253
+ total = options[:total_entries]
254
+ [page, per_page, total]
255
+ end
256
+
257
+ private
258
+
259
+ # def find_every_with_paginate(options)
260
+ # @options_from_last_find = options
261
+ # find_every_without_paginate(options)
262
+ # end
263
+ end
264
+ end
265
+ end
@@ -0,0 +1,170 @@
1
+ module WillPaginate
2
+ # This is a feature backported from Rails 2.1 because of its usefullness not only with will_paginate,
3
+ # but in other aspects when managing complex conditions that you want to be reusable.
4
+ module NamedScope
5
+ # All subclasses of ActiveRecord::Base have two named_scopes:
6
+ # * <tt>all</tt>, which is similar to a <tt>find(:all)</tt> query, and
7
+ # * <tt>scoped</tt>, which allows for the creation of anonymous scopes, on the fly: <tt>Shirt.scoped(:conditions => {:color => 'red'}).scoped(:include => :washing_instructions)</tt>
8
+ #
9
+ # These anonymous scopes tend to be useful when procedurally generating complex queries, where passing
10
+ # intermediate values (scopes) around as first-class objects is convenient.
11
+ def self.included(base)
12
+ base.class_eval do
13
+ extend ClassMethods
14
+ named_scope :scoped, lambda { |scope| scope }
15
+ end
16
+ end
17
+
18
+ module ClassMethods
19
+ def scopes
20
+ read_inheritable_attribute(:scopes) || write_inheritable_attribute(:scopes, {})
21
+ end
22
+
23
+ # Adds a class method for retrieving and querying objects. A scope represents a narrowing of a database query,
24
+ # such as <tt>:conditions => {:color => :red}, :select => 'shirts.*', :include => :washing_instructions</tt>.
25
+ #
26
+ # class Shirt < ActiveRecord::Base
27
+ # named_scope :red, :conditions => {:color => 'red'}
28
+ # named_scope :dry_clean_only, :joins => :washing_instructions, :conditions => ['washing_instructions.dry_clean_only = ?', true]
29
+ # end
30
+ #
31
+ # The above calls to <tt>named_scope</tt> define class methods <tt>Shirt.red</tt> and <tt>Shirt.dry_clean_only</tt>. <tt>Shirt.red</tt>,
32
+ # in effect, represents the query <tt>Shirt.find(:all, :conditions => {:color => 'red'})</tt>.
33
+ #
34
+ # Unlike Shirt.find(...), however, the object returned by <tt>Shirt.red</tt> is not an Array; it resembles the association object
35
+ # constructed by a <tt>has_many</tt> declaration. For instance, you can invoke <tt>Shirt.red.find(:first)</tt>, <tt>Shirt.red.count</tt>,
36
+ # <tt>Shirt.red.find(:all, :conditions => {:size => 'small'})</tt>. Also, just
37
+ # as with the association objects, name scopes acts like an Array, implementing Enumerable; <tt>Shirt.red.each(&block)</tt>,
38
+ # <tt>Shirt.red.first</tt>, and <tt>Shirt.red.inject(memo, &block)</tt> all behave as if Shirt.red really were an Array.
39
+ #
40
+ # These named scopes are composable. For instance, <tt>Shirt.red.dry_clean_only</tt> will produce all shirts that are both red and dry clean only.
41
+ # Nested finds and calculations also work with these compositions: <tt>Shirt.red.dry_clean_only.count</tt> returns the number of garments
42
+ # for which these criteria obtain. Similarly with <tt>Shirt.red.dry_clean_only.average(:thread_count)</tt>.
43
+ #
44
+ # All scopes are available as class methods on the ActiveRecord::Base descendent upon which the scopes were defined. But they are also available to
45
+ # <tt>has_many</tt> associations. If,
46
+ #
47
+ # class Person < ActiveRecord::Base
48
+ # has_many :shirts
49
+ # end
50
+ #
51
+ # then <tt>elton.shirts.red.dry_clean_only</tt> will return all of Elton's red, dry clean
52
+ # only shirts.
53
+ #
54
+ # Named scopes can also be procedural.
55
+ #
56
+ # class Shirt < ActiveRecord::Base
57
+ # named_scope :colored, lambda { |color|
58
+ # { :conditions => { :color => color } }
59
+ # }
60
+ # end
61
+ #
62
+ # In this example, <tt>Shirt.colored('puce')</tt> finds all puce shirts.
63
+ #
64
+ # Named scopes can also have extensions, just as with <tt>has_many</tt> declarations:
65
+ #
66
+ # class Shirt < ActiveRecord::Base
67
+ # named_scope :red, :conditions => {:color => 'red'} do
68
+ # def dom_id
69
+ # 'red_shirts'
70
+ # end
71
+ # end
72
+ # end
73
+ #
74
+ #
75
+ # For testing complex named scopes, you can examine the scoping options using the
76
+ # <tt>proxy_options</tt> method on the proxy itself.
77
+ #
78
+ # class Shirt < ActiveRecord::Base
79
+ # named_scope :colored, lambda { |color|
80
+ # { :conditions => { :color => color } }
81
+ # }
82
+ # end
83
+ #
84
+ # expected_options = { :conditions => { :colored => 'red' } }
85
+ # assert_equal expected_options, Shirt.colored('red').proxy_options
86
+ def named_scope(name, options = {})
87
+ name = name.to_sym
88
+ scopes[name] = lambda do |parent_scope, *args|
89
+ Scope.new(parent_scope, case options
90
+ when Hash
91
+ options
92
+ when Proc
93
+ options.call(*args)
94
+ end) { |*a| yield(*a) if block_given? }
95
+ end
96
+ (class << self; self end).instance_eval do
97
+ define_method name do |*args|
98
+ scopes[name].call(self, *args)
99
+ end
100
+ end
101
+ end
102
+ end
103
+
104
+ class Scope
105
+ attr_reader :proxy_scope, :proxy_options
106
+
107
+ [].methods.each do |m|
108
+ unless m =~ /(^__|^nil\?|^send|^object_id$|class|extend|^find$|count|sum|average|maximum|minimum|paginate|first|last|empty\?|respond_to\?)/
109
+ delegate m, :to => :proxy_found
110
+ end
111
+ end
112
+
113
+ delegate :scopes, :with_scope, :to => :proxy_scope
114
+
115
+ def initialize(proxy_scope, options)
116
+ [options[:extend]].flatten.each { |extension| extend extension } if options[:extend]
117
+ extend Module.new { |*args| yield(*args) } if block_given?
118
+ @proxy_scope, @proxy_options = proxy_scope, options.except(:extend)
119
+ end
120
+
121
+ def reload
122
+ load_found; self
123
+ end
124
+
125
+ def first(*args)
126
+ if args.first.kind_of?(Integer) || (@found && !args.first.kind_of?(Hash))
127
+ proxy_found.first(*args)
128
+ else
129
+ find(:first, *args)
130
+ end
131
+ end
132
+
133
+ def last(*args)
134
+ if args.first.kind_of?(Integer) || (@found && !args.first.kind_of?(Hash))
135
+ proxy_found.last(*args)
136
+ else
137
+ find(:last, *args)
138
+ end
139
+ end
140
+
141
+ def empty?
142
+ @found ? @found.empty? : count.zero?
143
+ end
144
+
145
+ def respond_to?(method, include_private = false)
146
+ super || @proxy_scope.respond_to?(method, include_private)
147
+ end
148
+
149
+ protected
150
+ def proxy_found
151
+ @found || load_found
152
+ end
153
+
154
+ private
155
+ def method_missing(method, *args)
156
+ if scopes.include?(method)
157
+ scopes[method].call(self, *args)
158
+ else
159
+ with_scope :find => proxy_options do
160
+ proxy_scope.send(method, *args) { |*a| yield(*a) if block_given? }
161
+ end
162
+ end
163
+ end
164
+
165
+ def load_found
166
+ @found = find(:all)
167
+ end
168
+ end
169
+ end
170
+ end