dweinand-will_paginate 2.3.4

Sign up to get free protection for your applications and to get access to all the features.
Files changed (45) hide show
  1. data/CHANGELOG.rdoc +100 -0
  2. data/LICENSE +18 -0
  3. data/README.rdoc +196 -0
  4. data/Rakefile +62 -0
  5. data/examples/apple-circle.gif +0 -0
  6. data/examples/index.haml +69 -0
  7. data/examples/index.html +92 -0
  8. data/examples/pagination.css +90 -0
  9. data/examples/pagination.sass +91 -0
  10. data/init.rb +1 -0
  11. data/lib/will_paginate/array.rb +16 -0
  12. data/lib/will_paginate/collection.rb +175 -0
  13. data/lib/will_paginate/core_ext.rb +32 -0
  14. data/lib/will_paginate/deserializer.rb +97 -0
  15. data/lib/will_paginate/finder.rb +256 -0
  16. data/lib/will_paginate/named_scope.rb +132 -0
  17. data/lib/will_paginate/named_scope_patch.rb +39 -0
  18. data/lib/will_paginate/version.rb +9 -0
  19. data/lib/will_paginate/view_helpers.rb +383 -0
  20. data/lib/will_paginate.rb +94 -0
  21. data/test/boot.rb +22 -0
  22. data/test/collection_test.rb +161 -0
  23. data/test/console +8 -0
  24. data/test/database.yml +22 -0
  25. data/test/finder_test.rb +448 -0
  26. data/test/fixtures/admin.rb +3 -0
  27. data/test/fixtures/developer.rb +14 -0
  28. data/test/fixtures/developers_projects.yml +13 -0
  29. data/test/fixtures/project.rb +15 -0
  30. data/test/fixtures/projects.yml +6 -0
  31. data/test/fixtures/replies.yml +29 -0
  32. data/test/fixtures/reply.rb +7 -0
  33. data/test/fixtures/schema.rb +38 -0
  34. data/test/fixtures/topic.rb +6 -0
  35. data/test/fixtures/topics.yml +30 -0
  36. data/test/fixtures/user.rb +2 -0
  37. data/test/fixtures/users.yml +35 -0
  38. data/test/helper.rb +42 -0
  39. data/test/lib/activerecord_test_case.rb +36 -0
  40. data/test/lib/activerecord_test_connector.rb +73 -0
  41. data/test/lib/load_fixtures.rb +11 -0
  42. data/test/lib/view_test_process.rb +165 -0
  43. data/test/tasks.rake +59 -0
  44. data/test/view_test.rb +363 -0
  45. metadata +133 -0
@@ -0,0 +1,132 @@
1
+ ## stolen from: http://dev.rubyonrails.org/browser/trunk/activerecord/lib/active_record/named_scope.rb?rev=9084
2
+
3
+ module WillPaginate
4
+ # This is a feature backported from Rails 2.1 because of its usefullness not only with will_paginate,
5
+ # but in other aspects when managing complex conditions that you want to be reusable.
6
+ module NamedScope
7
+ # All subclasses of ActiveRecord::Base have two named_scopes:
8
+ # * <tt>all</tt>, which is similar to a <tt>find(:all)</tt> query, and
9
+ # * <tt>scoped</tt>, which allows for the creation of anonymous scopes, on the fly:
10
+ #
11
+ # Shirt.scoped(:conditions => {:color => 'red'}).scoped(:include => :washing_instructions)
12
+ #
13
+ # These anonymous scopes tend to be useful when procedurally generating complex queries, where passing
14
+ # intermediate values (scopes) around as first-class objects is convenient.
15
+ def self.included(base)
16
+ base.class_eval do
17
+ extend ClassMethods
18
+ named_scope :all
19
+ named_scope :scoped, lambda { |scope| scope }
20
+ end
21
+ end
22
+
23
+ module ClassMethods
24
+ def scopes #:nodoc:
25
+ read_inheritable_attribute(:scopes) || write_inheritable_attribute(:scopes, {})
26
+ end
27
+
28
+ # Adds a class method for retrieving and querying objects. A scope represents a narrowing of a database query,
29
+ # such as <tt>:conditions => {:color => :red}, :select => 'shirts.*', :include => :washing_instructions</tt>.
30
+ #
31
+ # class Shirt < ActiveRecord::Base
32
+ # named_scope :red, :conditions => {:color => 'red'}
33
+ # named_scope :dry_clean_only, :joins => :washing_instructions, :conditions => ['washing_instructions.dry_clean_only = ?', true]
34
+ # end
35
+ #
36
+ # 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>,
37
+ # in effect, represents the query <tt>Shirt.find(:all, :conditions => {:color => 'red'})</tt>.
38
+ #
39
+ # Unlike Shirt.find(...), however, the object returned by <tt>Shirt.red</tt> is not an Array; it resembles the association object
40
+ # constructed by a <tt>has_many</tt> declaration. For instance, you can invoke <tt>Shirt.red.find(:first)</tt>, <tt>Shirt.red.count</tt>,
41
+ # <tt>Shirt.red.find(:all, :conditions => {:size => 'small'})</tt>. Also, just
42
+ # as with the association objects, name scopes acts like an Array, implementing Enumerable; <tt>Shirt.red.each(&block)</tt>,
43
+ # <tt>Shirt.red.first</tt>, and <tt>Shirt.red.inject(memo, &block)</tt> all behave as if Shirt.red really were an Array.
44
+ #
45
+ # 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.
46
+ # Nested finds and calculations also work with these compositions: <tt>Shirt.red.dry_clean_only.count</tt> returns the number of garments
47
+ # for which these criteria obtain. Similarly with <tt>Shirt.red.dry_clean_only.average(:thread_count)</tt>.
48
+ #
49
+ # All scopes are available as class methods on the ActiveRecord descendent upon which the scopes were defined. But they are also available to
50
+ # <tt>has_many</tt> associations. If,
51
+ #
52
+ # class Person < ActiveRecord::Base
53
+ # has_many :shirts
54
+ # end
55
+ #
56
+ # then <tt>elton.shirts.red.dry_clean_only</tt> will return all of Elton's red, dry clean
57
+ # only shirts.
58
+ #
59
+ # Named scopes can also be procedural.
60
+ #
61
+ # class Shirt < ActiveRecord::Base
62
+ # named_scope :colored, lambda { |color|
63
+ # { :conditions => { :color => color } }
64
+ # }
65
+ # end
66
+ #
67
+ # In this example, <tt>Shirt.colored('puce')</tt> finds all puce shirts.
68
+ #
69
+ # Named scopes can also have extensions, just as with <tt>has_many</tt> declarations:
70
+ #
71
+ # class Shirt < ActiveRecord::Base
72
+ # named_scope :red, :conditions => {:color => 'red'} do
73
+ # def dom_id
74
+ # 'red_shirts'
75
+ # end
76
+ # end
77
+ # end
78
+ #
79
+ def named_scope(name, options = {}, &block)
80
+ scopes[name] = lambda do |parent_scope, *args|
81
+ Scope.new(parent_scope, case options
82
+ when Hash
83
+ options
84
+ when Proc
85
+ options.call(*args)
86
+ end, &block)
87
+ end
88
+ (class << self; self end).instance_eval do
89
+ define_method name do |*args|
90
+ scopes[name].call(self, *args)
91
+ end
92
+ end
93
+ end
94
+ end
95
+
96
+ class Scope #:nodoc:
97
+ attr_reader :proxy_scope, :proxy_options
98
+ [].methods.each { |m| delegate m, :to => :proxy_found unless m =~ /(^__|^nil\?|^send|class|extend|find|count|sum|average|maximum|minimum|paginate)/ }
99
+ delegate :scopes, :with_scope, :to => :proxy_scope
100
+
101
+ def initialize(proxy_scope, options, &block)
102
+ [options[:extend]].flatten.each { |extension| extend extension } if options[:extend]
103
+ extend Module.new(&block) if block_given?
104
+ @proxy_scope, @proxy_options = proxy_scope, options.except(:extend)
105
+ end
106
+
107
+ def reload
108
+ load_found; self
109
+ end
110
+
111
+ protected
112
+ def proxy_found
113
+ @found || load_found
114
+ end
115
+
116
+ private
117
+ def method_missing(method, *args, &block)
118
+ if scopes.include?(method)
119
+ scopes[method].call(self, *args)
120
+ else
121
+ with_scope :find => proxy_options do
122
+ proxy_scope.send(method, *args, &block)
123
+ end
124
+ end
125
+ end
126
+
127
+ def load_found
128
+ @found = find(:all)
129
+ end
130
+ end
131
+ end
132
+ end
@@ -0,0 +1,39 @@
1
+ ## based on http://dev.rubyonrails.org/changeset/9084
2
+
3
+ ActiveRecord::Associations::AssociationProxy.class_eval do
4
+ protected
5
+ def with_scope(*args, &block)
6
+ @reflection.klass.send :with_scope, *args, &block
7
+ end
8
+ end
9
+
10
+ [ ActiveRecord::Associations::AssociationCollection,
11
+ ActiveRecord::Associations::HasManyThroughAssociation ].each do |klass|
12
+ klass.class_eval do
13
+ protected
14
+ alias :method_missing_without_scopes :method_missing_without_paginate
15
+ def method_missing_without_paginate(method, *args, &block)
16
+ if @reflection.klass.scopes.include?(method)
17
+ @reflection.klass.scopes[method].call(self, *args, &block)
18
+ else
19
+ method_missing_without_scopes(method, *args, &block)
20
+ end
21
+ end
22
+ end
23
+ end
24
+
25
+ # Rails 1.2.6
26
+ ActiveRecord::Associations::HasAndBelongsToManyAssociation.class_eval do
27
+ protected
28
+ def method_missing(method, *args, &block)
29
+ if @target.respond_to?(method) || (!@reflection.klass.respond_to?(method) && Class.respond_to?(method))
30
+ super
31
+ elsif @reflection.klass.scopes.include?(method)
32
+ @reflection.klass.scopes[method].call(self, *args)
33
+ else
34
+ @reflection.klass.with_scope(:find => { :conditions => @finder_sql, :joins => @join_sql, :readonly => false }) do
35
+ @reflection.klass.send(method, *args, &block)
36
+ end
37
+ end
38
+ end
39
+ end if ActiveRecord::Base.respond_to? :find_first
@@ -0,0 +1,9 @@
1
+ module WillPaginate
2
+ module VERSION
3
+ MAJOR = 2
4
+ MINOR = 3
5
+ TINY = 3
6
+
7
+ STRING = [MAJOR, MINOR, TINY].join('.')
8
+ end
9
+ end
@@ -0,0 +1,383 @@
1
+ require 'will_paginate/core_ext'
2
+
3
+ module WillPaginate
4
+ # = Will Paginate view helpers
5
+ #
6
+ # The main view helper, #will_paginate, renders
7
+ # pagination links for the given collection. The helper itself is lightweight
8
+ # and serves only as a wrapper around LinkRenderer instantiation; the
9
+ # renderer then does all the hard work of generating the HTML.
10
+ #
11
+ # == Global options for helpers
12
+ #
13
+ # Options for pagination helpers are optional and get their default values from the
14
+ # <tt>WillPaginate::ViewHelpers.pagination_options</tt> hash. You can write to this hash to
15
+ # override default options on the global level:
16
+ #
17
+ # WillPaginate::ViewHelpers.pagination_options[:previous_label] = 'Previous page'
18
+ #
19
+ # By putting this into "config/initializers/will_paginate.rb" (or simply environment.rb in
20
+ # older versions of Rails) you can easily translate link texts to previous
21
+ # and next pages, as well as override some other defaults to your liking.
22
+ module ViewHelpers
23
+ # default options that can be overridden on the global level
24
+ @@pagination_options = {
25
+ :class => 'pagination',
26
+ :previous_label => '&laquo; Previous',
27
+ :next_label => 'Next &raquo;',
28
+ :inner_window => 4, # links around the current page
29
+ :outer_window => 1, # links around beginning and end
30
+ :separator => ' ', # single space is friendly to spiders and non-graphic browsers
31
+ :param_name => :page,
32
+ :params => nil,
33
+ :renderer => 'WillPaginate::LinkRenderer',
34
+ :page_links => true,
35
+ :container => true
36
+ }
37
+ mattr_reader :pagination_options
38
+
39
+ # Renders Digg/Flickr-style pagination for a WillPaginate::Collection
40
+ # object. Nil is returned if there is only one page in total; no point in
41
+ # rendering the pagination in that case...
42
+ #
43
+ # ==== Options
44
+ # Display options:
45
+ # * <tt>:previous_label</tt> -- default: "« Previous" (this parameter is called <tt>:prev_label</tt> in versions <b>2.3.2</b> and older!)
46
+ # * <tt>:next_label</tt> -- default: "Next »"
47
+ # * <tt>:page_links</tt> -- when false, only previous/next links are rendered (default: true)
48
+ # * <tt>:inner_window</tt> -- how many links are shown around the current page (default: 4)
49
+ # * <tt>:outer_window</tt> -- how many links are around the first and the last page (default: 1)
50
+ # * <tt>:separator</tt> -- string separator for page HTML elements (default: single space)
51
+ #
52
+ # HTML options:
53
+ # * <tt>:class</tt> -- CSS class name for the generated DIV (default: "pagination")
54
+ # * <tt>:container</tt> -- toggles rendering of the DIV container for pagination links, set to
55
+ # false only when you are rendering your own pagination markup (default: true)
56
+ # * <tt>:id</tt> -- HTML ID for the container (default: nil). Pass +true+ to have the ID
57
+ # automatically generated from the class name of objects in collection: for example, paginating
58
+ # ArticleComment models would yield an ID of "article_comments_pagination".
59
+ #
60
+ # Advanced options:
61
+ # * <tt>:param_name</tt> -- parameter name for page number in URLs (default: <tt>:page</tt>)
62
+ # * <tt>:params</tt> -- additional parameters when generating pagination links
63
+ # (eg. <tt>:controller => "foo", :action => nil</tt>)
64
+ # * <tt>:renderer</tt> -- class name, class or instance of a link renderer (default:
65
+ # <tt>WillPaginate::LinkRenderer</tt>)
66
+ #
67
+ # All options not recognized by will_paginate will become HTML attributes on the container
68
+ # element for pagination links (the DIV). For example:
69
+ #
70
+ # <%= will_paginate @posts, :style => 'font-size: small' %>
71
+ #
72
+ # ... will result in:
73
+ #
74
+ # <div class="pagination" style="font-size: small"> ... </div>
75
+ #
76
+ # ==== Using the helper without arguments
77
+ # If the helper is called without passing in the collection object, it will
78
+ # try to read from the instance variable inferred by the controller name.
79
+ # For example, calling +will_paginate+ while the current controller is
80
+ # PostsController will result in trying to read from the <tt>@posts</tt>
81
+ # variable. Example:
82
+ #
83
+ # <%= will_paginate :id => true %>
84
+ #
85
+ # ... will result in <tt>@post</tt> collection getting paginated:
86
+ #
87
+ # <div class="pagination" id="posts_pagination"> ... </div>
88
+ #
89
+ def will_paginate(collection = nil, options = {})
90
+ options, collection = collection, nil if collection.is_a? Hash
91
+ unless collection or !controller
92
+ collection_name = "@#{controller.controller_name}"
93
+ collection = instance_variable_get(collection_name)
94
+ raise ArgumentError, "The #{collection_name} variable appears to be empty. Did you " +
95
+ "forget to pass the collection object for will_paginate?" unless collection
96
+ end
97
+ # early exit if there is nothing to render
98
+ return nil unless WillPaginate::ViewHelpers.total_pages_for_collection(collection) > 1
99
+
100
+ options = options.symbolize_keys.reverse_merge WillPaginate::ViewHelpers.pagination_options
101
+ if options[:prev_label]
102
+ WillPaginate::Deprecation::warn(":prev_label view parameter is now :previous_label; the old name has been deprecated.")
103
+ options[:previous_label] = options.delete(:prev_label)
104
+ end
105
+
106
+ # get the renderer instance
107
+ renderer = case options[:renderer]
108
+ when String
109
+ options[:renderer].to_s.constantize.new
110
+ when Class
111
+ options[:renderer].new
112
+ else
113
+ options[:renderer]
114
+ end
115
+ # render HTML for pagination
116
+ renderer.prepare collection, options, self
117
+ renderer.to_html
118
+ end
119
+
120
+ # Wrapper for rendering pagination links at both top and bottom of a block
121
+ # of content.
122
+ #
123
+ # <% paginated_section @posts do %>
124
+ # <ol id="posts">
125
+ # <% for post in @posts %>
126
+ # <li> ... </li>
127
+ # <% end %>
128
+ # </ol>
129
+ # <% end %>
130
+ #
131
+ # will result in:
132
+ #
133
+ # <div class="pagination"> ... </div>
134
+ # <ol id="posts">
135
+ # ...
136
+ # </ol>
137
+ # <div class="pagination"> ... </div>
138
+ #
139
+ # Arguments are passed to a <tt>will_paginate</tt> call, so the same options
140
+ # apply. Don't use the <tt>:id</tt> option; otherwise you'll finish with two
141
+ # blocks of pagination links sharing the same ID (which is invalid HTML).
142
+ def paginated_section(*args, &block)
143
+ pagination = will_paginate(*args).to_s
144
+ content = pagination + capture(&block) + pagination
145
+ concat content, block.binding
146
+ end
147
+
148
+ # Renders a helpful message with numbers of displayed vs. total entries.
149
+ # You can use this as a blueprint for your own, similar helpers.
150
+ #
151
+ # <%= page_entries_info @posts %>
152
+ # #-> Displaying posts 6 - 10 of 26 in total
153
+ #
154
+ # By default, the message will use the humanized class name of objects
155
+ # in collection: for instance, "project types" for ProjectType models.
156
+ # Override this with the <tt>:entry_name</tt> parameter:
157
+ #
158
+ # <%= page_entries_info @posts, :entry_name => 'item' %>
159
+ # #-> Displaying items 6 - 10 of 26 in total
160
+ def page_entries_info(collection, options = {})
161
+ entry_name = options[:entry_name] ||
162
+ (collection.empty?? 'entry' : collection.first.class.name.underscore.sub('_', ' '))
163
+
164
+ if collection.total_pages < 2
165
+ case collection.size
166
+ when 0; "No #{entry_name.pluralize} found"
167
+ when 1; "Displaying <b>1</b> #{entry_name}"
168
+ else; "Displaying <b>all #{collection.size}</b> #{entry_name.pluralize}"
169
+ end
170
+ else
171
+ %{Displaying #{entry_name.pluralize} <b>%d&nbsp;-&nbsp;%d</b> of <b>%d</b> in total} % [
172
+ collection.offset + 1,
173
+ collection.offset + collection.length,
174
+ collection.total_entries
175
+ ]
176
+ end
177
+ end
178
+
179
+ def self.total_pages_for_collection(collection) #:nodoc:
180
+ if collection.respond_to?('page_count') and !collection.respond_to?('total_pages')
181
+ WillPaginate::Deprecation.warn <<-MSG
182
+ You are using a paginated collection of class #{collection.class.name}
183
+ which conforms to the old API of WillPaginate::Collection by using
184
+ `page_count`, while the current method name is `total_pages`. Please
185
+ upgrade yours or 3rd-party code that provides the paginated collection.
186
+ MSG
187
+ class << collection
188
+ def total_pages; page_count; end
189
+ end
190
+ end
191
+ collection.total_pages
192
+ end
193
+ end
194
+
195
+ # This class does the heavy lifting of actually building the pagination
196
+ # links. It is used by the <tt>will_paginate</tt> helper internally.
197
+ class LinkRenderer
198
+
199
+ # The gap in page links is represented by:
200
+ #
201
+ # <span class="gap">&hellip;</span>
202
+ attr_accessor :gap_marker
203
+
204
+ def initialize
205
+ @gap_marker = '<span class="gap">&hellip;</span>'
206
+ end
207
+
208
+ # * +collection+ is a WillPaginate::Collection instance or any other object
209
+ # that conforms to that API
210
+ # * +options+ are forwarded from +will_paginate+ view helper
211
+ # * +template+ is the reference to the template being rendered
212
+ def prepare(collection, options, template)
213
+ @collection = collection
214
+ @options = options
215
+ @template = template
216
+
217
+ # reset values in case we're re-using this instance
218
+ @total_pages = @param_name = @url_string = nil
219
+ end
220
+
221
+ # Process it! This method returns the complete HTML string which contains
222
+ # pagination links. Feel free to subclass LinkRenderer and change this
223
+ # method as you see fit.
224
+ def to_html
225
+ links = @options[:page_links] ? windowed_links : []
226
+ # previous/next buttons
227
+ links.unshift page_link_or_span(@collection.previous_page, 'disabled prev_page', @options[:previous_label])
228
+ links.push page_link_or_span(@collection.next_page, 'disabled next_page', @options[:next_label])
229
+
230
+ html = links.join(@options[:separator])
231
+ @options[:container] ? @template.content_tag(:div, html, html_attributes) : html
232
+ end
233
+
234
+ # Returns the subset of +options+ this instance was initialized with that
235
+ # represent HTML attributes for the container element of pagination links.
236
+ def html_attributes
237
+ return @html_attributes if @html_attributes
238
+ @html_attributes = @options.except *(WillPaginate::ViewHelpers.pagination_options.keys - [:class])
239
+ # pagination of Post models will have the ID of "posts_pagination"
240
+ if @options[:container] and @options[:id] === true
241
+ @html_attributes[:id] = @collection.first.class.name.underscore.pluralize + '_pagination'
242
+ end
243
+ @html_attributes
244
+ end
245
+
246
+ protected
247
+
248
+ # Collects link items for visible page numbers.
249
+ def windowed_links
250
+ prev = nil
251
+
252
+ visible_page_numbers.inject [] do |links, n|
253
+ # detect gaps:
254
+ links << gap_marker if prev and n > prev + 1
255
+ links << page_link_or_span(n, 'current')
256
+ prev = n
257
+ links
258
+ end
259
+ end
260
+
261
+ # Calculates visible page numbers using the <tt>:inner_window</tt> and
262
+ # <tt>:outer_window</tt> options.
263
+ def visible_page_numbers
264
+ inner_window, outer_window = @options[:inner_window].to_i, @options[:outer_window].to_i
265
+ window_from = current_page - inner_window
266
+ window_to = current_page + inner_window
267
+
268
+ # adjust lower or upper limit if other is out of bounds
269
+ if window_to > total_pages
270
+ window_from -= window_to - total_pages
271
+ window_to = total_pages
272
+ end
273
+ if window_from < 1
274
+ window_to += 1 - window_from
275
+ window_from = 1
276
+ window_to = total_pages if window_to > total_pages
277
+ end
278
+
279
+ visible = (1..total_pages).to_a
280
+ left_gap = (2 + outer_window)...window_from
281
+ right_gap = (window_to + 1)...(total_pages - outer_window)
282
+ visible -= left_gap.to_a if left_gap.last - left_gap.first > 1
283
+ visible -= right_gap.to_a if right_gap.last - right_gap.first > 1
284
+
285
+ visible
286
+ end
287
+
288
+ def page_link_or_span(page, span_class, text = nil)
289
+ text ||= page.to_s
290
+
291
+ if page and page != current_page
292
+ classnames = span_class && span_class.index(' ') && span_class.split(' ', 2).last
293
+ page_link page, text, :rel => rel_value(page), :class => classnames
294
+ else
295
+ page_span page, text, :class => span_class
296
+ end
297
+ end
298
+
299
+ def page_link(page, text, attributes = {})
300
+ @template.link_to text, url_for(page), attributes
301
+ end
302
+
303
+ def page_span(page, text, attributes = {})
304
+ @template.content_tag :span, text, attributes
305
+ end
306
+
307
+ # Returns URL params for +page_link_or_span+, taking the current GET params
308
+ # and <tt>:params</tt> option into account.
309
+ def url_for(page)
310
+ page_one = page == 1
311
+ unless @url_string and !page_one
312
+ @url_params = {}
313
+ # page links should preserve GET parameters
314
+ stringified_merge @url_params, @template.params if @template.request.get?
315
+ stringified_merge @url_params, @options[:params] if @options[:params]
316
+
317
+ if complex = param_name.index(/[^\w-]/)
318
+ page_param = (defined?(CGIMethods) ? CGIMethods : ActionController::AbstractRequest).
319
+ parse_query_parameters("#{param_name}=#{page}")
320
+
321
+ stringified_merge @url_params, page_param
322
+ else
323
+ @url_params[param_name] = page_one ? 1 : 2
324
+ end
325
+
326
+ url = @template.url_for(@url_params)
327
+ return url if page_one
328
+
329
+ if complex
330
+ @url_string = url.sub(%r!((?:\?|&amp;)#{CGI.escape param_name}=)#{page}!, '\1@')
331
+ return url
332
+ else
333
+ @url_string = url
334
+ @url_params[param_name] = 3
335
+ @template.url_for(@url_params).split(//).each_with_index do |char, i|
336
+ if char == '3' and url[i, 1] == '2'
337
+ @url_string[i] = '@'
338
+ break
339
+ end
340
+ end
341
+ end
342
+ end
343
+ # finally!
344
+ @url_string.sub '@', page.to_s
345
+ end
346
+
347
+ private
348
+
349
+ def rel_value(page)
350
+ case page
351
+ when @collection.previous_page; 'prev' + (page == 1 ? ' start' : '')
352
+ when @collection.next_page; 'next'
353
+ when 1; 'start'
354
+ end
355
+ end
356
+
357
+ def current_page
358
+ @collection.current_page
359
+ end
360
+
361
+ def total_pages
362
+ @total_pages ||= WillPaginate::ViewHelpers.total_pages_for_collection(@collection)
363
+ end
364
+
365
+ def param_name
366
+ @param_name ||= @options[:param_name].to_s
367
+ end
368
+
369
+ # Recursively merge into target hash by using stringified keys from the other one
370
+ def stringified_merge(target, other)
371
+ other.each do |key, value|
372
+ key = key.to_s # this line is what it's all about!
373
+ existing = target[key]
374
+
375
+ if value.is_a?(Hash) and (existing.is_a?(Hash) or existing.nil?)
376
+ stringified_merge(existing || (target[key] = {}), value)
377
+ else
378
+ target[key] = value
379
+ end
380
+ end
381
+ end
382
+ end
383
+ end
@@ -0,0 +1,94 @@
1
+ require 'active_support'
2
+
3
+ # = You *will* paginate!
4
+ #
5
+ # First read about WillPaginate::Finder::ClassMethods, then see
6
+ # WillPaginate::ViewHelpers. The magical array you're handling in-between is
7
+ # WillPaginate::Collection.
8
+ #
9
+ # Happy paginating!
10
+ module WillPaginate
11
+ class << self
12
+ # shortcut for <tt>enable_actionpack</tt> and <tt>enable_activerecord</tt> combined
13
+ def enable
14
+ enable_actionpack
15
+ enable_activerecord
16
+ enable_activeresource
17
+ end
18
+
19
+ # hooks WillPaginate::ViewHelpers into ActionView::Base
20
+ def enable_actionpack
21
+ return if ActionView::Base.instance_methods.include? 'will_paginate'
22
+ require 'will_paginate/view_helpers'
23
+ ActionView::Base.send :include, ViewHelpers
24
+
25
+ if defined?(ActionController::Base) and ActionController::Base.respond_to? :rescue_responses
26
+ ActionController::Base.rescue_responses['WillPaginate::InvalidPage'] = :not_found
27
+ end
28
+ end
29
+
30
+ # hooks WillPaginate::Finder into ActiveRecord::Base and classes that deal
31
+ # with associations
32
+ def enable_activerecord
33
+ return if ActiveRecord::Base.respond_to? :paginate
34
+ require 'will_paginate/finder'
35
+ ActiveRecord::Base.send :include, Finder
36
+
37
+ # support pagination on associations
38
+ a = ActiveRecord::Associations
39
+ returning([ a::AssociationCollection ]) { |classes|
40
+ # detect http://dev.rubyonrails.org/changeset/9230
41
+ unless a::HasManyThroughAssociation.superclass == a::HasManyAssociation
42
+ classes << a::HasManyThroughAssociation
43
+ end
44
+ }.each do |klass|
45
+ klass.send :include, Finder::ClassMethods
46
+ klass.class_eval { alias_method_chain :method_missing, :paginate }
47
+ end
48
+ end
49
+
50
+ def enable_activeresource
51
+ unless defined?(ActiveResource::Base)
52
+ $stderr.puts "Can't find ActiveResource. `gem install activeresource` to correct this."
53
+ return
54
+ end
55
+
56
+ return if ActiveResource::Base.respond_to? :instantiate_collection_with_collection
57
+ require 'will_paginate/deserializer'
58
+ ActiveResource::Base.class_eval { include Deserializer }
59
+ end
60
+
61
+ # Enable named_scope, a feature of Rails 2.1, even if you have older Rails
62
+ # (tested on Rails 2.0.2 and 1.2.6).
63
+ #
64
+ # You can pass +false+ for +patch+ parameter to skip monkeypatching
65
+ # *associations*. Use this if you feel that <tt>named_scope</tt> broke
66
+ # has_many, has_many :through or has_and_belongs_to_many associations in
67
+ # your app. By passing +false+, you can still use <tt>named_scope</tt> in
68
+ # your models, but not through associations.
69
+ def enable_named_scope(patch = true)
70
+ return if defined? ActiveRecord::NamedScope
71
+ require 'will_paginate/named_scope'
72
+ require 'will_paginate/named_scope_patch' if patch
73
+
74
+ ActiveRecord::Base.send :include, WillPaginate::NamedScope
75
+ end
76
+ end
77
+
78
+ module Deprecation # :nodoc:
79
+ extend ActiveSupport::Deprecation
80
+
81
+ def self.warn(message, callstack = caller)
82
+ message = 'WillPaginate: ' + message.strip.gsub(/\s+/, ' ')
83
+ behavior.call(message, callstack) if behavior && !silenced?
84
+ end
85
+
86
+ def self.silenced?
87
+ ActiveSupport::Deprecation.silenced?
88
+ end
89
+ end
90
+ end
91
+
92
+ if defined?(Rails) and defined?(ActiveRecord) and defined?(ActionController)
93
+ WillPaginate.enable
94
+ end
data/test/boot.rb ADDED
@@ -0,0 +1,22 @@
1
+ plugin_root = File.join(File.dirname(__FILE__), '..')
2
+ version = ENV['RAILS_VERSION']
3
+ version = nil if version and version == ""
4
+
5
+ # first look for a symlink to a copy of the framework
6
+ if !version and framework_root = ["#{plugin_root}/rails", "#{plugin_root}/../../rails"].find { |p| File.directory? p }
7
+ puts "found framework root: #{framework_root}"
8
+ # this allows for a plugin to be tested outside of an app and without Rails gems
9
+ $:.unshift "#{framework_root}/activesupport/lib", "#{framework_root}/activerecord/lib", "#{framework_root}/actionpack/lib", "#{framework_root}/activeresource/lib"
10
+ else
11
+ # simply use installed gems if available
12
+ puts "using Rails#{version ? ' ' + version : nil} gems"
13
+ require 'rubygems'
14
+
15
+ if version
16
+ gem 'rails', version
17
+ else
18
+ gem 'actionpack'
19
+ gem 'activerecord'
20
+ gem 'activeresource'
21
+ end
22
+ end