From 48ab5e4517edb81816a45918e6c0d7d3a40f9f2c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mislav=20Marohni=C4=87?= Date: Fri, 9 May 2008 02:43:24 +0200 Subject: [PATCH 001/168] don't require ActiveSupport. start converting tests to spec --- Rakefile | 1 + lib/will_paginate.rb | 15 +--- lib/will_paginate/deprecation.rb | 48 ++++++++++ spec/collection_spec.rb | 147 +++++++++++++++++++++++++++++++ spec/spec.opts | 2 + spec/spec_helper.rb | 10 +++ spec/tasks.rake | 39 ++++++++ test/collection_test.rb | 140 ----------------------------- 8 files changed, 248 insertions(+), 154 deletions(-) create mode 100644 lib/will_paginate/deprecation.rb create mode 100644 spec/collection_spec.rb create mode 100644 spec/spec.opts create mode 100644 spec/spec_helper.rb create mode 100644 spec/tasks.rake delete mode 100644 test/collection_test.rb diff --git a/Rakefile b/Rakefile index c3cf1c610..fba6bf4a1 100644 --- a/Rakefile +++ b/Rakefile @@ -8,6 +8,7 @@ rescue LoadError require 'rake/rdoctask' end load 'test/tasks.rake' +load 'spec/tasks.rake' desc 'Default: run unit tests.' task :default => :test diff --git a/lib/will_paginate.rb b/lib/will_paginate.rb index 366e39cc9..f26616803 100644 --- a/lib/will_paginate.rb +++ b/lib/will_paginate.rb @@ -1,4 +1,4 @@ -require 'active_support' +require 'will_paginate/deprecation' # = You *will* paginate! # @@ -66,19 +66,6 @@ def enable_named_scope(patch = true) end end end - - module Deprecation #:nodoc: - extend ActiveSupport::Deprecation - - def self.warn(message, callstack = caller) - message = 'WillPaginate: ' + message.strip.gsub(/\s+/, ' ') - behavior.call(message, callstack) if behavior && !silenced? - end - - def self.silenced? - ActiveSupport::Deprecation.silenced? - end - end end if defined?(Rails) and defined?(ActiveRecord) and defined?(ActionController) diff --git a/lib/will_paginate/deprecation.rb b/lib/will_paginate/deprecation.rb new file mode 100644 index 000000000..3aea2765c --- /dev/null +++ b/lib/will_paginate/deprecation.rb @@ -0,0 +1,48 @@ +# borrowed from ActiveSupport::Deprecation +module WillPaginate + module Deprecation + mattr_accessor :debug + self.debug = false + + # Choose the default warn behavior according to RAILS_ENV. + # Ignore deprecation warnings in production. + BEHAVIORS = { + 'test' => Proc.new { |message, callstack| + $stderr.puts(message) + $stderr.puts callstack.join("\n ") if debug + }, + 'development' => Proc.new { |message, callstack| + logger = defined?(::RAILS_DEFAULT_LOGGER) ? ::RAILS_DEFAULT_LOGGER : Logger.new($stderr) + logger.warn message + logger.debug callstack.join("\n ") if debug + } + } + + def self.warn(message, callstack = caller) + if behavior + message = 'WillPaginate: ' + message.strip.gsub(/\s+/, ' ') + behavior.call(message, callstack) + end + end + + def self.default_behavior + if defined?(RAILS_ENV) + BEHAVIORS[RAILS_ENV.to_s] + else + BEHAVIORS['test'] + end + end + + # Behavior is a block that takes a message argument. + mattr_accessor :behavior + self.behavior = default_behavior + + def self.silence + old_behavior = self.behavior + self.behavior = nil + yield + ensure + self.behavior = old_behavior + end + end +end diff --git a/spec/collection_spec.rb b/spec/collection_spec.rb new file mode 100644 index 000000000..4d71dc90f --- /dev/null +++ b/spec/collection_spec.rb @@ -0,0 +1,147 @@ +require 'will_paginate/array' +require 'spec_helper' + +describe WillPaginate::Collection do + + before :all do + @simple = ('a'..'e').to_a + end + + it "should be a subset of original collection" do + @simple.paginate(:page => 1, :per_page => 3).should == %w( a b c ) + end + + it "can be shorter than per_page if on last page" do + @simple.paginate(:page => 2, :per_page => 3).should == %w( d e ) + end + + it "should include whole collection if per_page permits" do + @simple.paginate(:page => 1, :per_page => 5).should == @simple + end + + it "should be empty if out of bounds" do + @simple.paginate(:page => 2, :per_page => 5).should be_empty + end + + it "should default to 1 as current page and 30 per-page" do + result = (1..50).to_a.paginate + result.current_page.should == 1 + result.size.should == 30 + end + + describe "old API" do + it "should fail with numeric params" do + Proc.new { [].paginate(2) }.should raise_error(ArgumentError) + Proc.new { [].paginate(2, 10) }.should raise_error(ArgumentError) + end + + it "should fail with both options and numeric param" do + Proc.new { [].paginate({}, 5) }.should raise_error(ArgumentError) + end + end + + it "should give total_entries precedence over actual size" do + %w(a b c).paginate(:total_entries => 5).total_entries.should == 5 + end + + it "should be an augmented Array" do + entries = %w(a b c) + collection = create(2, 3, 10) do |pager| + pager.replace(entries).should == entries + end + + collection.should == entries + for method in %w(total_pages each offset size current_page per_page total_entries) + collection.should respond_to(method) + end + collection.should be_kind_of(Array) + collection.entries.should be_instance_of(Array) + # TODO: move to another expectation: + collection.offset.should == 3 + collection.total_pages.should == 4 + collection.should_not be_out_of_bounds + end + + describe "previous/next pages" do + it "should have previous_page nil when on first page" do + collection = create(1, 1, 3) + collection.previous_page.should be_nil + collection.next_page.should == 2 + end + + it "should have both prev/next pages" do + collection = create(2, 1, 3) + collection.previous_page.should == 1 + collection.next_page.should == 3 + end + + it "should have next_page nil when on last page" do + collection = create(3, 1, 3) + collection.previous_page.should == 2 + collection.next_page.should be_nil + end + end + + it "should show out of bounds when page number is too high" do + create(2, 3, 2).should be_out_of_bounds + end + + it "should not show out of bounds when inside collection" do + create(1, 3, 2).should_not be_out_of_bounds + end + + describe "guessing total count" do + it "can guess when collection is shorter than limit" do + collection = create { |p| p.replace array } + collection.total_entries.should == 8 + end + + it "should allow explicit total count to override guessed" do + collection = create(2, 5, 10) { |p| p.replace array } + collection.total_entries.should == 10 + end + + it "should not be able to guess when collection is same as limit" do + collection = create { |p| p.replace array(5) } + collection.total_entries.should be_nil + end + + it "should not be able to guess when collection is empty" do + collection = create { |p| p.replace array(0) } + collection.total_entries.should be_nil + end + + it "should be able to guess when collection is empty and this is the first page" do + collection = create(1) { |p| p.replace array(0) } + collection.total_entries.should == 0 + end + end + + it "should raise WillPaginate::InvalidPage on invalid input" do + for bad_input in [0, -1, nil, '', 'Schnitzel'] + Proc.new { create bad_input }.should raise_error(WillPaginate::InvalidPage) + end + end + + it "should raise Argument error on invalid per_page setting" do + Proc.new { create(1, -1) }.should raise_error(ArgumentError) + end + + it "should not respond to page_count anymore" do + Proc.new { create.page_count }.should raise_error(NoMethodError) + end + + private + + def create(page = 2, limit = 5, total = nil, &block) + if block_given? + WillPaginate::Collection.create(page, limit, total, &block) + else + WillPaginate::Collection.new(page, limit, total) + end + end + + def array(size = 3) + Array.new(size) + end +end diff --git a/spec/spec.opts b/spec/spec.opts new file mode 100644 index 000000000..14f5f1316 --- /dev/null +++ b/spec/spec.opts @@ -0,0 +1,2 @@ +--colour +--reverse diff --git a/spec/spec_helper.rb b/spec/spec_helper.rb new file mode 100644 index 000000000..b16f15342 --- /dev/null +++ b/spec/spec_helper.rb @@ -0,0 +1,10 @@ +require 'rubygems' +gem 'rspec', '~> 1.1.3' +require 'spec' + +Spec::Runner.configure do |config| + # config.include My::Pony, My::Horse, :type => :farm + # config.predicate_matchers[:swim] = :can_swim? + + config.mock_with :mocha +end diff --git a/spec/tasks.rake b/spec/tasks.rake new file mode 100644 index 000000000..a60cd39b8 --- /dev/null +++ b/spec/tasks.rake @@ -0,0 +1,39 @@ +require 'spec/rake/spectask' + +spec_opts = 'spec/spec.opts' +spec_glob = FileList['spec/**/*_spec.rb'] + +desc 'Run all specs in spec directory' +Spec::Rake::SpecTask.new(:spec) do |t| + t.libs << 'lib' << 'spec' + t.spec_opts = ['--options', spec_opts] + t.spec_files = spec_glob +end + +namespace :spec do + desc 'Run all specs in spec directory with RCov' + Spec::Rake::SpecTask.new(:rcov) do |t| + t.libs << 'lib' << 'spec' + t.spec_opts = ['--options', spec_opts] + t.spec_files = spec_glob + t.rcov = true + # t.rcov_opts = lambda do + # IO.readlines('spec/rcov.opts').map {|l| l.chomp.split " "}.flatten + # end + end + + desc 'Print Specdoc for all specs' + Spec::Rake::SpecTask.new(:doc) do |t| + t.libs << 'lib' << 'spec' + t.spec_opts = ['--format', 'specdoc', '--dry-run'] + t.spec_files = spec_glob + end + + desc 'Generate HTML report' + Spec::Rake::SpecTask.new(:html) do |t| + t.libs << 'lib' << 'spec' + t.spec_opts = ['--format', 'html:doc/spec_results.html', '--diff'] + t.spec_files = spec_glob + t.fail_on_error = false + end +end diff --git a/test/collection_test.rb b/test/collection_test.rb deleted file mode 100644 index b33609015..000000000 --- a/test/collection_test.rb +++ /dev/null @@ -1,140 +0,0 @@ -require 'helper' -require 'will_paginate/array' - -class ArrayPaginationTest < Test::Unit::TestCase - def test_simple - collection = ('a'..'e').to_a - - [{ :page => 1, :per_page => 3, :expected => %w( a b c ) }, - { :page => 2, :per_page => 3, :expected => %w( d e ) }, - { :page => 1, :per_page => 5, :expected => %w( a b c d e ) }, - { :page => 3, :per_page => 5, :expected => [] }, - ]. - each do |conditions| - expected = conditions.delete :expected - assert_equal expected, collection.paginate(conditions) - end - end - - def test_defaults - result = (1..50).to_a.paginate - assert_equal 1, result.current_page - assert_equal 30, result.size - end - - def test_deprecated_api - assert_raise(ArgumentError) { [].paginate(2) } - assert_raise(ArgumentError) { [].paginate(2, 10) } - end - - def test_total_entries_has_precedence - result = %w(a b c).paginate :total_entries => 5 - assert_equal 5, result.total_entries - end - - def test_argument_error_with_params_and_another_argument - assert_raise ArgumentError do - [].paginate({}, 5) - end - end - - def test_paginated_collection - entries = %w(a b c) - collection = create(2, 3, 10) do |pager| - assert_equal entries, pager.replace(entries) - end - - assert_equal entries, collection - assert_respond_to_all collection, %w(total_pages each offset size current_page per_page total_entries) - assert_kind_of Array, collection - assert_instance_of Array, collection.entries - assert_equal 3, collection.offset - assert_equal 4, collection.total_pages - assert !collection.out_of_bounds? - end - - def test_previous_next_pages - collection = create(1, 1, 3) - assert_nil collection.previous_page - assert_equal 2, collection.next_page - - collection = create(2, 1, 3) - assert_equal 1, collection.previous_page - assert_equal 3, collection.next_page - - collection = create(3, 1, 3) - assert_equal 2, collection.previous_page - assert_nil collection.next_page - end - - def test_out_of_bounds - entries = create(2, 3, 2){} - assert entries.out_of_bounds? - - entries = create(1, 3, 2){} - assert !entries.out_of_bounds? - end - - def test_guessing_total_count - entries = create do |pager| - # collection is shorter than limit - pager.replace array - end - assert_equal 8, entries.total_entries - - entries = create(2, 5, 10) do |pager| - # collection is shorter than limit, but we have an explicit count - pager.replace array - end - assert_equal 10, entries.total_entries - - entries = create do |pager| - # collection is the same as limit; we can't guess - pager.replace array(5) - end - assert_equal nil, entries.total_entries - - entries = create do |pager| - # collection is empty; we can't guess - pager.replace array(0) - end - assert_equal nil, entries.total_entries - - entries = create(1) do |pager| - # collection is empty and we're on page 1, - # so the whole thing must be empty, too - pager.replace array(0) - end - assert_equal 0, entries.total_entries - end - - def test_invalid_page - bad_inputs = [0, -1, nil, '', 'Schnitzel'] - - bad_inputs.each do |bad| - assert_raise(WillPaginate::InvalidPage) { create bad } - end - end - - def test_invalid_per_page_setting - assert_raise(ArgumentError) { create(1, -1) } - end - - def test_page_count_was_removed - assert_raise(NoMethodError) { create.page_count } - # It's `total_pages` now. - end - - private - def create(page = 2, limit = 5, total = nil, &block) - if block_given? - WillPaginate::Collection.create(page, limit, total, &block) - else - WillPaginate::Collection.new(page, limit, total) - end - end - - def array(size = 3) - Array.new(size) - end -end From 97af7cbd4769c917f5aa9387f977234da1f99a99 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mislav=20Marohni=C4=87?= Date: Fri, 9 May 2008 03:05:29 +0200 Subject: [PATCH 002/168] document Array#paginate --- Rakefile | 1 - lib/will_paginate/array.rb | 33 +++++++++++++++++++++++++-------- 2 files changed, 25 insertions(+), 9 deletions(-) diff --git a/Rakefile b/Rakefile index fba6bf4a1..d98e9600e 100644 --- a/Rakefile +++ b/Rakefile @@ -18,7 +18,6 @@ Rake::RDocTask.new(:rdoc) do |rdoc| rdoc.rdoc_files.include('README.rdoc', 'LICENSE', 'CHANGELOG'). include('lib/**/*.rb'). exclude('lib/will_paginate/named_scope*'). - exclude('lib/will_paginate/array.rb'). exclude('lib/will_paginate/version.rb') rdoc.main = "README.rdoc" # page to start on diff --git a/lib/will_paginate/array.rb b/lib/will_paginate/array.rb index d061d2be9..10767600d 100644 --- a/lib/will_paginate/array.rb +++ b/lib/will_paginate/array.rb @@ -1,16 +1,33 @@ require 'will_paginate/collection' -# http://www.desimcadam.com/archives/8 -Array.class_eval do +class Array + # Paginates a static array (extracting a subset of it). The result is a + # WillPaginate::Collection instance, which is an array with few more + # properties about its paginated state. + # + # Parameters: + # * :page - current page, defaults to 1 + # * :per_page - limit of items per page, defaults to 30 + # * :total_entries - total number of items in the array, defaults to + # array.length (obviously) + # + # Example: + # arr = ['a', 'b', 'c', 'd', 'e'] + # paged = arr.paginate(:per_page => 2) #-> ['a', 'b'] + # paged.total_entries #-> 5 + # arr.paginate(:page => 2, :per_page => 2) #-> ['c', 'd'] + # arr.paginate(:page => 3, :per_page => 2) #-> ['e'] + # + # This method was originally {suggested by Desi + # McAdam}[http://www.desimcadam.com/archives/8] and later proved to be the + # most useful method of will_paginate library. def paginate(options = {}) raise ArgumentError, "parameter hash expected (got #{options.inspect})" unless Hash === options - WillPaginate::Collection.create( - options[:page] || 1, - options[:per_page] || 30, - options[:total_entries] || self.length - ) { |pager| + WillPaginate::Collection.create options[:page] || 1, + options[:per_page] || 30, + options[:total_entries] || self.length do |pager| pager.replace self[pager.offset, pager.per_page].to_a - } + end end end From b2c9e8f04577953957fcde0149844ab23b951b40 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mislav=20Marohni=C4=87?= Date: Fri, 9 May 2008 04:47:59 +0200 Subject: [PATCH 003/168] no mattr_accessor, I don't use ActiveSupport anymore --- lib/will_paginate/deprecation.rb | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/lib/will_paginate/deprecation.rb b/lib/will_paginate/deprecation.rb index 3aea2765c..c05da9b41 100644 --- a/lib/will_paginate/deprecation.rb +++ b/lib/will_paginate/deprecation.rb @@ -1,7 +1,8 @@ # borrowed from ActiveSupport::Deprecation module WillPaginate module Deprecation - mattr_accessor :debug + def self.debug() @debug end + def self.debug=(value) @debug = value end self.debug = false # Choose the default warn behavior according to RAILS_ENV. @@ -34,7 +35,8 @@ def self.default_behavior end # Behavior is a block that takes a message argument. - mattr_accessor :behavior + def self.debug() @behavior end + def self.behavior=(value) @behavior = value end self.behavior = default_behavior def self.silence From 5a67bfd556b4b92b3ad4b4008d080c5a16feda40 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mislav=20Marohni=C4=87?= Date: Fri, 9 May 2008 04:49:05 +0200 Subject: [PATCH 004/168] split finder.rb into Finders::Common and Finders::ActiveRecord --- lib/will_paginate.rb | 28 +-- lib/will_paginate/finder.rb | 236 +-------------------- lib/will_paginate/finders/active_record.rb | 159 ++++++++++++++ lib/will_paginate/finders/common.rb | 89 ++++++++ test/finder_test.rb | 2 +- test/lib/load_fixtures.rb | 3 +- 6 files changed, 255 insertions(+), 262 deletions(-) create mode 100644 lib/will_paginate/finders/active_record.rb create mode 100644 lib/will_paginate/finders/common.rb diff --git a/lib/will_paginate.rb b/lib/will_paginate.rb index f26616803..3f54ce95a 100644 --- a/lib/will_paginate.rb +++ b/lib/will_paginate.rb @@ -12,7 +12,6 @@ class << self # shortcut for enable_actionpack; enable_activerecord def enable enable_actionpack - enable_activerecord end # mixes in WillPaginate::ViewHelpers in ActionView::Base @@ -25,28 +24,6 @@ def enable_actionpack ActionController::Base.rescue_responses['WillPaginate::InvalidPage'] = :not_found end end - - # mixes in WillPaginate::Finder in ActiveRecord::Base and classes that deal - # with associations - def enable_activerecord - return if ActiveRecord::Base.respond_to? :paginate - require 'will_paginate/finder' - ActiveRecord::Base.class_eval { include Finder } - - # support pagination on associations - a = ActiveRecord::Associations - returning([ a::AssociationCollection ]) { |classes| - # detect http://dev.rubyonrails.org/changeset/9230 - unless a::HasManyThroughAssociation.superclass == a::HasManyAssociation - classes << a::HasManyThroughAssociation - end - }.each do |klass| - klass.class_eval do - include Finder::ClassMethods - alias_method_chain :method_missing, :paginate - end - end - end # Enable named_scope, a feature of Rails 2.1, even if you have older Rails # (tested on Rails 2.0.2 and 1.2.6). @@ -68,6 +45,7 @@ def enable_named_scope(patch = true) end end -if defined?(Rails) and defined?(ActiveRecord) and defined?(ActionController) - WillPaginate.enable +if defined?(Rails) + WillPaginate.enable_actionpack if defined?(ActionController) + require 'will_paginate/finders/active_record' if defined?(ActiveRecord) end diff --git a/lib/will_paginate/finder.rb b/lib/will_paginate/finder.rb index 6aac7e699..24188e0dc 100644 --- a/lib/will_paginate/finder.rb +++ b/lib/will_paginate/finder.rb @@ -1,239 +1,7 @@ require 'will_paginate/core_ext' module WillPaginate - # A mixin for ActiveRecord::Base. Provides +per_page+ class method - # and hooks things up to provide paginating finders. - # - # Find out more in WillPaginate::Finder::ClassMethods - # - module Finder - def self.included(base) - base.extend ClassMethods - class << base - alias_method_chain :method_missing, :paginate - # alias_method_chain :find_every, :paginate - define_method(:per_page) { 30 } unless respond_to?(:per_page) - end - end - - # = Paginating finders for ActiveRecord models - # - # WillPaginate adds +paginate+, +per_page+ and other methods to - # ActiveRecord::Base class methods and associations. It also hooks into - # +method_missing+ to intercept pagination calls to dynamic finders such as - # +paginate_by_user_id+ and translate them to ordinary finders - # (+find_all_by_user_id+ in this case). - # - # In short, paginating finders are equivalent to ActiveRecord finders; the - # only difference is that we start with "paginate" instead of "find" and - # that :page is required parameter: - # - # @posts = Post.paginate :all, :page => params[:page], :order => 'created_at DESC' - # - # In paginating finders, "all" is implicit. There is no sense in paginating - # a single record, right? So, you can drop the :all argument: - # - # Post.paginate(...) => Post.find :all - # Post.paginate_all_by_something => Post.find_all_by_something - # Post.paginate_by_something => Post.find_all_by_something - # - # == The importance of the :order parameter - # - # In ActiveRecord finders, :order parameter specifies columns for - # the ORDER BY clause in SQL. It is important to have it, since - # pagination only makes sense with ordered sets. Without the ORDER - # BY clause, databases aren't required to do consistent ordering when - # performing SELECT queries; this is especially true for - # PostgreSQL. - # - # Therefore, make sure you are doing ordering on a column that makes the - # most sense in the current context. Make that obvious to the user, also. - # For perfomance reasons you will also want to add an index to that column. - module ClassMethods - # This is the main paginating finder. - # - # == Special parameters for paginating finders - # * :page -- REQUIRED, but defaults to 1 if false or nil - # * :per_page -- defaults to CurrentModel.per_page (which is 30 if not overridden) - # * :total_entries -- use only if you manually count total entries - # * :count -- additional options that are passed on to +count+ - # * :finder -- name of the ActiveRecord finder used (default: "find") - # - # All other options (+conditions+, +order+, ...) are forwarded to +find+ - # and +count+ calls. - def paginate(*args, &block) - options = args.pop - page, per_page, total_entries = wp_parse_options(options) - finder = (options[:finder] || 'find').to_s - - if finder == 'find' - # an array of IDs may have been given: - total_entries ||= (Array === args.first and args.first.size) - # :all is implicit - args.unshift(:all) if args.empty? - end - - WillPaginate::Collection.create(page, per_page, total_entries) do |pager| - count_options = options.except :page, :per_page, :total_entries, :finder - find_options = count_options.except(:count).update(:offset => pager.offset, :limit => pager.per_page) - - args << find_options - # @options_from_last_find = nil - pager.replace send(finder, *args, &block) - - # magic counting for user convenience: - pager.total_entries = wp_count(count_options, args, finder) unless pager.total_entries - end - end - - # Iterates through all records by loading one page at a time. This is useful - # for migrations or any other use case where you don't want to load all the - # records in memory at once. - # - # It uses +paginate+ internally; therefore it accepts all of its options. - # You can specify a starting page with :page (default is 1). Default - # :order is "id", override if necessary. - # - # See http://weblog.jamisbuck.org/2007/4/6/faking-cursors-in-activerecord where - # Jamis Buck describes this and also uses a more efficient way for MySQL. - def paginated_each(options = {}, &block) - options = { :order => 'id', :page => 1 }.merge options - options[:page] = options[:page].to_i - options[:total_entries] = 0 # skip the individual count queries - total = 0 - - begin - collection = paginate(options) - total += collection.each(&block).size - options[:page] += 1 - end until collection.size < collection.per_page - - total - end - - # Wraps +find_by_sql+ by simply adding LIMIT and OFFSET to your SQL string - # based on the params otherwise used by paginating finds: +page+ and - # +per_page+. - # - # Example: - # - # @developers = Developer.paginate_by_sql ['select * from developers where salary > ?', 80000], - # :page => params[:page], :per_page => 3 - # - # A query for counting rows will automatically be generated if you don't - # supply :total_entries. If you experience problems with this - # generated SQL, you might want to perform the count manually in your - # application. - # - def paginate_by_sql(sql, options) - WillPaginate::Collection.create(*wp_parse_options(options)) do |pager| - query = sanitize_sql(sql) - original_query = query.dup - # add limit, offset - add_limit! query, :offset => pager.offset, :limit => pager.per_page - # perfom the find - pager.replace find_by_sql(query) - - unless pager.total_entries - count_query = original_query.sub /\bORDER\s+BY\s+[\w`,\s]+$/mi, '' - count_query = "SELECT COUNT(*) FROM (#{count_query})" - - unless ['oracle', 'oci'].include?(self.connection.adapter_name.downcase) - count_query << ' AS count_table' - end - # perform the count query - pager.total_entries = count_by_sql(count_query) - end - end - end - - def respond_to?(method, include_priv = false) #:nodoc: - case method.to_sym - when :paginate, :paginate_by_sql - true - else - super(method.to_s.sub(/^paginate/, 'find'), include_priv) - end - end - - protected - - def method_missing_with_paginate(method, *args, &block) #:nodoc: - # did somebody tried to paginate? if not, let them be - unless method.to_s.index('paginate') == 0 - return method_missing_without_paginate(method, *args, &block) - end - - # paginate finders are really just find_* with limit and offset - finder = method.to_s.sub('paginate', 'find') - finder.sub!('find', 'find_all') if finder.index('find_by_') == 0 - - options = args.pop - raise ArgumentError, 'parameter hash expected' unless options.respond_to? :symbolize_keys - options = options.dup - options[:finder] = finder - args << options - - paginate(*args, &block) - end - - # Does the not-so-trivial job of finding out the total number of entries - # in the database. It relies on the ActiveRecord +count+ method. - def wp_count(options, args, finder) - excludees = [:count, :order, :limit, :offset, :readonly] - unless options[:select] and options[:select] =~ /^\s*DISTINCT\b/i - excludees << :select # only exclude the select param if it doesn't begin with DISTINCT - end - # count expects (almost) the same options as find - count_options = options.except *excludees - - # merge the hash found in :count - # this allows you to specify :select, :order, or anything else just for the count query - count_options.update options[:count] if options[:count] - - # we may have to scope ... - counter = Proc.new { count(count_options) } - - # we may be in a model or an association proxy! - klass = (@owner and @reflection) ? @reflection.klass : self - - count = if finder.index('find_') == 0 and klass.respond_to?(scoper = finder.sub('find', 'with')) - # scope_out adds a 'with_finder' method which acts like with_scope, if it's present - # then execute the count with the scoping provided by the with_finder - send(scoper, &counter) - elsif match = /^find_(all_by|by)_([_a-zA-Z]\w*)$/.match(finder) - # extract conditions from calls like "paginate_by_foo_and_bar" - attribute_names = extract_attribute_names_from_match(match) - conditions = construct_attributes_from_arguments(attribute_names, args) - with_scope(:find => { :conditions => conditions }, &counter) - else - counter.call - end - - count.respond_to?(:length) ? count.length : count - end - - def wp_parse_options(options) #:nodoc: - raise ArgumentError, 'parameter hash expected' unless options.respond_to? :symbolize_keys - options = options.symbolize_keys - raise ArgumentError, ':page parameter required' unless options.key? :page - - if options[:count] and options[:total_entries] - raise ArgumentError, ':count and :total_entries are mutually exclusive' - end - - page = options[:page] || 1 - per_page = options[:per_page] || self.per_page - total = options[:total_entries] - [page, per_page, total] - end - - private - - # def find_every_with_paginate(options) - # @options_from_last_find = options - # find_every_without_paginate(options) - # end - end + # Database logic for different ORMs + module Finders end end diff --git a/lib/will_paginate/finders/active_record.rb b/lib/will_paginate/finders/active_record.rb new file mode 100644 index 000000000..f18a8bdb5 --- /dev/null +++ b/lib/will_paginate/finders/active_record.rb @@ -0,0 +1,159 @@ +require 'will_paginate/finders/common' +require 'active_record' + +module WillPaginate::Finders + # = Paginating finders for ActiveRecord models + # + # WillPaginate adds +paginate+, +per_page+ and other methods to + # ActiveRecord::Base class methods and associations. It also hooks into + # +method_missing+ to intercept pagination calls to dynamic finders such as + # +paginate_by_user_id+ and translate them to ordinary finders + # (+find_all_by_user_id+ in this case). + # + # In short, paginating finders are equivalent to ActiveRecord finders; the + # only difference is that we start with "paginate" instead of "find" and + # that :page is required parameter: + # + # @posts = Post.paginate :all, :page => params[:page], :order => 'created_at DESC' + # + # In paginating finders, "all" is implicit. There is no sense in paginating + # a single record, right? So, you can drop the :all argument: + # + # Post.paginate(...) => Post.find :all + # Post.paginate_all_by_something => Post.find_all_by_something + # Post.paginate_by_something => Post.find_all_by_something + # + # == The importance of the :order parameter + # + # In ActiveRecord finders, :order parameter specifies columns for + # the ORDER BY clause in SQL. It is important to have it, since + # pagination only makes sense with ordered sets. Without the ORDER + # BY clause, databases aren't required to do consistent ordering when + # performing SELECT queries; this is especially true for + # PostgreSQL. + # + # Therefore, make sure you are doing ordering on a column that makes the + # most sense in the current context. Make that obvious to the user, also. + # For perfomance reasons you will also want to add an index to that column. + module ActiveRecord + include WillPaginate::Finders::Common + + # Wraps +find_by_sql+ by simply adding LIMIT and OFFSET to your SQL string + # based on the params otherwise used by paginating finds: +page+ and + # +per_page+. + # + # Example: + # + # @developers = Developer.paginate_by_sql ['select * from developers where salary > ?', 80000], + # :page => params[:page], :per_page => 3 + # + # A query for counting rows will automatically be generated if you don't + # supply :total_entries. If you experience problems with this + # generated SQL, you might want to perform the count manually in your + # application. + # + def paginate_by_sql(sql, options) + WillPaginate::Collection.create(*wp_parse_options(options)) do |pager| + query = sanitize_sql(sql) + original_query = query.dup + # add limit, offset + add_limit! query, :offset => pager.offset, :limit => pager.per_page + # perfom the find + pager.replace find_by_sql(query) + + unless pager.total_entries + count_query = original_query.sub /\bORDER\s+BY\s+[\w`,\s]+$/mi, '' + count_query = "SELECT COUNT(*) FROM (#{count_query})" + + unless ['oracle', 'oci'].include?(self.connection.adapter_name.downcase) + count_query << ' AS count_table' + end + # perform the count query + pager.total_entries = count_by_sql(count_query) + end + end + end + + def respond_to?(method, include_priv = false) #:nodoc: + super(method.to_s.sub(/^paginate/, 'find'), include_priv) + end + + protected + + def method_missing_with_paginate(method, *args, &block) #:nodoc: + # did somebody tried to paginate? if not, let them be + unless method.to_s.index('paginate') == 0 + return method_missing_without_paginate(method, *args, &block) + end + + # paginate finders are really just find_* with limit and offset + finder = method.to_s.sub('paginate', 'find') + finder.sub!('find', 'find_all') if finder.index('find_by_') == 0 + + options = args.pop + raise ArgumentError, 'parameter hash expected' unless options.respond_to? :symbolize_keys + options = options.dup + options[:finder] = finder + args << options + + paginate(*args, &block) + end + + # Does the not-so-trivial job of finding out the total number of entries + # in the database. It relies on the ActiveRecord +count+ method. + def wp_count(options, args, finder) + excludees = [:count, :order, :limit, :offset, :readonly] + unless options[:select] and options[:select] =~ /^\s*DISTINCT\b/i + excludees << :select # only exclude the select param if it doesn't begin with DISTINCT + end + # count expects (almost) the same options as find + count_options = options.except *excludees + + # merge the hash found in :count + # this allows you to specify :select, :order, or anything else just for the count query + count_options.update options[:count] if options[:count] + + # we may have to scope ... + counter = Proc.new { count(count_options) } + + # we may be in a model or an association proxy! + klass = (@owner and @reflection) ? @reflection.klass : self + + count = if finder.index('find_') == 0 and klass.respond_to?(scoper = finder.sub('find', 'with')) + # scope_out adds a 'with_finder' method which acts like with_scope, if it's present + # then execute the count with the scoping provided by the with_finder + send(scoper, &counter) + elsif match = /^find_(all_by|by)_([_a-zA-Z]\w*)$/.match(finder) + # extract conditions from calls like "paginate_by_foo_and_bar" + attribute_names = extract_attribute_names_from_match(match) + conditions = construct_attributes_from_arguments(attribute_names, args) + with_scope(:find => { :conditions => conditions }, &counter) + else + counter.call + end + + count.respond_to?(:length) ? count.length : count + end + end +end + +ActiveRecord::Base.class_eval do + extend WillPaginate::Finders::ActiveRecord + class << self + alias_method_chain :method_missing, :paginate + end +end + +# support pagination on associations +a = ActiveRecord::Associations +returning([ a::AssociationCollection ]) { |classes| + # detect http://dev.rubyonrails.org/changeset/9230 + unless a::HasManyThroughAssociation.superclass == a::HasManyAssociation + classes << a::HasManyThroughAssociation + end +}.each do |klass| + klass.class_eval do + include WillPaginate::Finders::ActiveRecord + alias_method_chain :method_missing, :paginate + end +end diff --git a/lib/will_paginate/finders/common.rb b/lib/will_paginate/finders/common.rb new file mode 100644 index 000000000..157227c97 --- /dev/null +++ b/lib/will_paginate/finders/common.rb @@ -0,0 +1,89 @@ +require 'will_paginate/core_ext' + +module WillPaginate + module Finders + # Database-agnostic finder logic + module Common + # Default per-page limit + def per_page() 30 end + + # This is the main paginating finder. + # + # == Special parameters for paginating finders + # * :page -- REQUIRED, but defaults to 1 if false or nil + # * :per_page -- defaults to CurrentModel.per_page (which is 30 if not overridden) + # * :total_entries -- use only if you manually count total entries + # * :count -- additional options that are passed on to +count+ + # * :finder -- name of the ActiveRecord finder used (default: "find") + # + # All other options (+conditions+, +order+, ...) are forwarded to +find+ + # and +count+ calls. + def paginate(*args, &block) + options = args.pop + page, per_page, total_entries = wp_parse_options(options) + finder = (options[:finder] || 'find').to_s + + if finder == 'find' + # an array of IDs may have been given: + total_entries ||= (Array === args.first and args.first.size) + # :all is implicit + args.unshift(:all) if args.empty? + end + + WillPaginate::Collection.create(page, per_page, total_entries) do |pager| + count_options = options.except :page, :per_page, :total_entries, :finder + find_options = count_options.except(:count).update(:offset => pager.offset, :limit => pager.per_page) + + args << find_options + pager.replace send(finder, *args, &block) + + # magic counting for user convenience: + pager.total_entries = wp_count(count_options, args, finder) unless pager.total_entries + end + end + + # Iterates through all records by loading one page at a time. This is useful + # for migrations or any other use case where you don't want to load all the + # records in memory at once. + # + # It uses +paginate+ internally; therefore it accepts all of its options. + # You can specify a starting page with :page (default is 1). Default + # :order is "id", override if necessary. + # + # {Jamis Buck describes this}[http://weblog.jamisbuck.org/2007/4/6/faking-cursors-in-activerecord] + # and also uses a more efficient way for MySQL. + def paginated_each(options = {}, &block) + options = { :order => 'id', :page => 1 }.merge options + options[:page] = options[:page].to_i + options[:total_entries] = 0 # skip the individual count queries + total = 0 + + begin + collection = paginate(options) + total += collection.each(&block).size + options[:page] += 1 + end until collection.size < collection.per_page + + total + end + + protected + + def wp_parse_options(options) #:nodoc: + raise ArgumentError, 'parameter hash expected' unless options.respond_to? :symbolize_keys + options = options.symbolize_keys + raise ArgumentError, ':page parameter required' unless options.key? :page + + if options[:count] and options[:total_entries] + raise ArgumentError, ':count and :total_entries are mutually exclusive' + end + + page = options[:page] || 1 + per_page = options[:per_page] || self.per_page + total = options[:total_entries] + [page, per_page, total] + end + + end + end +end diff --git a/test/finder_test.rb b/test/finder_test.rb index 055109c08..19581b2f9 100644 --- a/test/finder_test.rb +++ b/test/finder_test.rb @@ -2,7 +2,7 @@ require 'lib/activerecord_test_case' require 'will_paginate' -WillPaginate.enable_activerecord +require 'will_paginate/finders/active_record' WillPaginate.enable_named_scope class FinderTest < ActiveRecordTestCase diff --git a/test/lib/load_fixtures.rb b/test/lib/load_fixtures.rb index 10d6f4209..bb164f0bf 100644 --- a/test/lib/load_fixtures.rb +++ b/test/lib/load_fixtures.rb @@ -7,5 +7,4 @@ # load all fixtures Fixtures.create_fixtures(ActiveRecordTestConnector::FIXTURES_PATH, ActiveRecord::Base.connection.tables) -require 'will_paginate' -WillPaginate.enable_activerecord +require 'will_paginate/finders/active_record' From a1efc6e86741313d3766acc3892a5ff9ae6103b5 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mislav=20Marohni=C4=87?= Date: Fri, 9 May 2008 05:33:50 +0200 Subject: [PATCH 005/168] extract last traces of ActiveRecord from Finders::Common to Finders::ActiveRecord --- lib/will_paginate/deprecation.rb | 8 ++++---- lib/will_paginate/{finder.rb => finders.rb} | 0 lib/will_paginate/finders/active_record.rb | 20 ++++++++++++++++++++ lib/will_paginate/finders/common.rb | 20 +++----------------- 4 files changed, 27 insertions(+), 21 deletions(-) rename lib/will_paginate/{finder.rb => finders.rb} (100%) diff --git a/lib/will_paginate/deprecation.rb b/lib/will_paginate/deprecation.rb index c05da9b41..2c44d1e60 100644 --- a/lib/will_paginate/deprecation.rb +++ b/lib/will_paginate/deprecation.rb @@ -1,8 +1,8 @@ # borrowed from ActiveSupport::Deprecation module WillPaginate module Deprecation - def self.debug() @debug end - def self.debug=(value) @debug = value end + def self.debug() @debug; end + def self.debug=(value) @debug = value; end self.debug = false # Choose the default warn behavior according to RAILS_ENV. @@ -35,8 +35,8 @@ def self.default_behavior end # Behavior is a block that takes a message argument. - def self.debug() @behavior end - def self.behavior=(value) @behavior = value end + def self.behavior() @behavior; end + def self.behavior=(value) @behavior = value; end self.behavior = default_behavior def self.silence diff --git a/lib/will_paginate/finder.rb b/lib/will_paginate/finders.rb similarity index 100% rename from lib/will_paginate/finder.rb rename to lib/will_paginate/finders.rb diff --git a/lib/will_paginate/finders/active_record.rb b/lib/will_paginate/finders/active_record.rb index f18a8bdb5..5e065a37a 100644 --- a/lib/will_paginate/finders/active_record.rb +++ b/lib/will_paginate/finders/active_record.rb @@ -99,6 +99,26 @@ def method_missing_with_paginate(method, *args, &block) #:nodoc: paginate(*args, &block) end + def wp_query(options, pager, args, &block) + finder = (options.delete(:finder) || 'find').to_s + find_options = options.except(:count).update(:offset => pager.offset, :limit => pager.per_page) + + if finder == 'find' + if Array === args.first and !pager.total_entries + pager.total_entries = args.first.size + end + args << :all if args.empty? + end + + args << find_options + pager.replace send(finder, *args, &block) + + unless pager.total_entries + # magic counting + pager.total_entries = wp_count(options, args, finder) + end + end + # Does the not-so-trivial job of finding out the total number of entries # in the database. It relies on the ActiveRecord +count+ method. def wp_count(options, args, finder) diff --git a/lib/will_paginate/finders/common.rb b/lib/will_paginate/finders/common.rb index 157227c97..1551408c7 100644 --- a/lib/will_paginate/finders/common.rb +++ b/lib/will_paginate/finders/common.rb @@ -14,31 +14,17 @@ def per_page() 30 end # * :per_page -- defaults to CurrentModel.per_page (which is 30 if not overridden) # * :total_entries -- use only if you manually count total entries # * :count -- additional options that are passed on to +count+ - # * :finder -- name of the ActiveRecord finder used (default: "find") + # * :finder -- name of the finder method to use (default: "find") # # All other options (+conditions+, +order+, ...) are forwarded to +find+ # and +count+ calls. def paginate(*args, &block) options = args.pop page, per_page, total_entries = wp_parse_options(options) - finder = (options[:finder] || 'find').to_s - - if finder == 'find' - # an array of IDs may have been given: - total_entries ||= (Array === args.first and args.first.size) - # :all is implicit - args.unshift(:all) if args.empty? - end WillPaginate::Collection.create(page, per_page, total_entries) do |pager| - count_options = options.except :page, :per_page, :total_entries, :finder - find_options = count_options.except(:count).update(:offset => pager.offset, :limit => pager.per_page) - - args << find_options - pager.replace send(finder, *args, &block) - - # magic counting for user convenience: - pager.total_entries = wp_count(count_options, args, finder) unless pager.total_entries + query_options = options.except :page, :per_page, :total_entries + wp_query(query_options, pager, args, &block) end end From 1624b01e7d1e793492403b46dc187b6bccd5de7e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mislav=20Marohni=C4=87?= Date: Fri, 9 May 2008 05:49:44 +0200 Subject: [PATCH 006/168] pagination for DataMapper --- lib/will_paginate/finders/data_mapper.rb | 36 ++++++++++++++++++++++++ 1 file changed, 36 insertions(+) create mode 100644 lib/will_paginate/finders/data_mapper.rb diff --git a/lib/will_paginate/finders/data_mapper.rb b/lib/will_paginate/finders/data_mapper.rb new file mode 100644 index 000000000..127394b15 --- /dev/null +++ b/lib/will_paginate/finders/data_mapper.rb @@ -0,0 +1,36 @@ +require 'will_paginate/finders/common' +require 'data_mapper' + +module WillPaginate::Finders + module DataMapper + include WillPaginate::Finders::Common + + protected + + def wp_query(options, pager, args, &block) + find_options = options.except(:count).update(:offset => pager.offset, :limit => pager.per_page) + + pager.replace all(find_options, &block) + + unless pager.total_entries + pager.total_entries = wp_count(options) + end + end + + # Does the not-so-trivial job of finding out the total number of entries + # in the database. It relies on the ActiveRecord +count+ method. + def wp_count(options, args, finder) + excludees = [:count, :order, :limit, :offset, :readonly] + count_options = options.except *excludees + + # merge the hash found in :count + count_options.update options[:count] if options[:count] + + count_options.empty?? count() : count(count_options) + end + end +end + +DataMapper::Base.class_eval do + include WillPaginate::Finders::DataMapper +end From 03068ffbaec05ba726232de68606e879793e0d40 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mislav=20Marohni=C4=87?= Date: Fri, 9 May 2008 06:50:55 +0200 Subject: [PATCH 007/168] start refactoring view_helpers.rb into ViewHelpers submodules --- lib/will_paginate.rb | 52 +-- lib/will_paginate/view_helpers.rb | 333 +----------------- lib/will_paginate/view_helpers/action_view.rb | 74 ++++ lib/will_paginate/view_helpers/common.rb | 103 ++++++ .../view_helpers/link_renderer.rb | 152 ++++++++ .../view_helpers/link_renderer_base.rb | 71 ++++ test/lib/view_test_process.rb | 3 +- test/view_test.rb | 4 +- 8 files changed, 428 insertions(+), 364 deletions(-) create mode 100644 lib/will_paginate/view_helpers/action_view.rb create mode 100644 lib/will_paginate/view_helpers/common.rb create mode 100644 lib/will_paginate/view_helpers/link_renderer.rb create mode 100644 lib/will_paginate/view_helpers/link_renderer_base.rb diff --git a/lib/will_paginate.rb b/lib/will_paginate.rb index 3f54ce95a..b27f9ec32 100644 --- a/lib/will_paginate.rb +++ b/lib/will_paginate.rb @@ -8,44 +8,30 @@ # # Happy paginating! module WillPaginate - class << self - # shortcut for enable_actionpack; enable_activerecord - def enable - enable_actionpack - end - - # mixes in WillPaginate::ViewHelpers in ActionView::Base - def enable_actionpack - return if ActionView::Base.instance_methods.include? 'will_paginate' - require 'will_paginate/view_helpers' - ActionView::Base.class_eval { include ViewHelpers } - - if defined?(ActionController::Base) and ActionController::Base.respond_to? :rescue_responses - ActionController::Base.rescue_responses['WillPaginate::InvalidPage'] = :not_found - end - end + # no-op + def self.enable + end - # Enable named_scope, a feature of Rails 2.1, even if you have older Rails - # (tested on Rails 2.0.2 and 1.2.6). - # - # You can pass +false+ for +patch+ parameter to skip monkeypatching - # *associations*. Use this if you feel that named_scope broke - # has_many, has_many :through or has_and_belongs_to_many associations in - # your app. By passing +false+, you can still use named_scope in - # your models, but not through associations. - def enable_named_scope(patch = true) - return if defined? ActiveRecord::NamedScope - require 'will_paginate/named_scope' - require 'will_paginate/named_scope_patch' if patch + # Enable named_scope, a feature of Rails 2.1, even if you have older Rails + # (tested on Rails 2.0.2 and 1.2.6). + # + # You can pass +false+ for +patch+ parameter to skip monkeypatching + # *associations*. Use this if you feel that named_scope broke + # has_many, has_many :through or has_and_belongs_to_many associations in + # your app. By passing +false+, you can still use named_scope in + # your models, but not through associations. + def self.enable_named_scope(patch = true) + return if defined? ActiveRecord::NamedScope + require 'will_paginate/named_scope' + require 'will_paginate/named_scope_patch' if patch - ActiveRecord::Base.class_eval do - include WillPaginate::NamedScope - end + ActiveRecord::Base.class_eval do + include WillPaginate::NamedScope end end end if defined?(Rails) - WillPaginate.enable_actionpack if defined?(ActionController) - require 'will_paginate/finders/active_record' if defined?(ActiveRecord) + require 'will_paginate/view_helpers/action_view' if defined?(ActionController) + require 'will_paginate/finders/active_record' if defined?(ActiveRecord) end diff --git a/lib/will_paginate/view_helpers.rb b/lib/will_paginate/view_helpers.rb index 0cd74359c..83dfd1a27 100644 --- a/lib/will_paginate/view_helpers.rb +++ b/lib/will_paginate/view_helpers.rb @@ -1,4 +1,4 @@ -require 'will_paginate/core_ext' +require 'will_paginate/deprecation' module WillPaginate # = Will Paginate view helpers @@ -19,8 +19,11 @@ module WillPaginate # By putting this into your environment.rb you can easily translate link texts to previous # and next pages, as well as override some other defaults to your liking. module ViewHelpers + def self.pagination_options() @pagination_options; end + def self.pagination_options=(value) @pagination_options = value; end + # default options that can be overridden on the global level - @@pagination_options = { + self.pagination_options = { :class => 'pagination', :prev_label => '« Previous', :next_label => 'Next »', @@ -29,142 +32,10 @@ module ViewHelpers :separator => ' ', # single space is friendly to spiders and non-graphic browsers :param_name => :page, :params => nil, - :renderer => 'WillPaginate::LinkRenderer', + :renderer => 'WillPaginate::ViewHelpers::LinkRenderer', :page_links => true, :container => true } - mattr_reader :pagination_options - - # Renders Digg/Flickr-style pagination for a WillPaginate::Collection - # object. Nil is returned if there is only one page in total; no point in - # rendering the pagination in that case... - # - # ==== Options - # * :class -- CSS class name for the generated DIV (default: "pagination") - # * :prev_label -- default: "« Previous" - # * :next_label -- default: "Next »" - # * :inner_window -- how many links are shown around the current page (default: 4) - # * :outer_window -- how many links are around the first and the last page (default: 1) - # * :separator -- string separator for page HTML elements (default: single space) - # * :param_name -- parameter name for page number in URLs (default: :page) - # * :params -- additional parameters when generating pagination links - # (eg. :controller => "foo", :action => nil) - # * :renderer -- class name, class or instance of a link renderer (default: - # WillPaginate::LinkRenderer) - # * :page_links -- when false, only previous/next links are rendered (default: true) - # * :container -- toggles rendering of the DIV container for pagination links, set to - # false only when you are rendering your own pagination markup (default: true) - # * :id -- HTML ID for the container (default: nil). Pass +true+ to have the ID - # automatically generated from the class name of objects in collection: for example, paginating - # ArticleComment models would yield an ID of "article_comments_pagination". - # - # All options beside listed ones are passed as HTML attributes to the container - # element for pagination links (the DIV). For example: - # - # <%= will_paginate @posts, :id => 'wp_posts' %> - # - # ... will result in: - # - # - # - # ==== Using the helper without arguments - # If the helper is called without passing in the collection object, it will - # try to read from the instance variable inferred by the controller name. - # For example, calling +will_paginate+ while the current controller is - # PostsController will result in trying to read from the @posts - # variable. Example: - # - # <%= will_paginate :id => true %> - # - # ... will result in @post collection getting paginated: - # - # - # - def will_paginate(collection = nil, options = {}) - options, collection = collection, nil if collection.is_a? Hash - unless collection or !controller - collection_name = "@#{controller.controller_name}" - collection = instance_variable_get(collection_name) - raise ArgumentError, "The #{collection_name} variable appears to be empty. Did you " + - "forget to pass the collection object for will_paginate?" unless collection - end - # early exit if there is nothing to render - return nil unless WillPaginate::ViewHelpers.total_pages_for_collection(collection) > 1 - - options = options.symbolize_keys.reverse_merge WillPaginate::ViewHelpers.pagination_options - - # get the renderer instance - renderer = case options[:renderer] - when String - options[:renderer].to_s.constantize.new - when Class - options[:renderer].new - else - options[:renderer] - end - # render HTML for pagination - renderer.prepare collection, options, self - renderer.to_html - end - - # Wrapper for rendering pagination links at both top and bottom of a block - # of content. - # - # <% paginated_section @posts do %> - #
    - # <% for post in @posts %> - #
  1. ...
  2. - # <% end %> - #
- # <% end %> - # - # will result in: - # - # - #
    - # ... - #
- # - # - # Arguments are passed to a will_paginate call, so the same options - # apply. Don't use the :id option; otherwise you'll finish with two - # blocks of pagination links sharing the same ID (which is invalid HTML). - def paginated_section(*args, &block) - pagination = will_paginate(*args).to_s - content = pagination + capture(&block) + pagination - concat content, block.binding - end - - # Renders a helpful message with numbers of displayed vs. total entries. - # You can use this as a blueprint for your own, similar helpers. - # - # <%= page_entries_info @posts %> - # #-> Displaying posts 6 - 10 of 26 in total - # - # By default, the message will use the humanized class name of objects - # in collection: for instance, "project types" for ProjectType models. - # Override this to your liking with the :entry_name parameter: - # - # <%= page_entries_info @posts, :entry_name => 'item' %> - # #-> Displaying items 6 - 10 of 26 in total - def page_entries_info(collection, options = {}) - entry_name = options[:entry_name] || - (collection.empty?? 'entry' : collection.first.class.name.underscore.sub('_', ' ')) - - if collection.total_pages < 2 - case collection.size - when 0; "No #{entry_name.pluralize} found" - when 1; "Displaying 1 #{entry_name}" - else; "Displaying all #{collection.size} #{entry_name.pluralize}" - end - else - %{Displaying #{entry_name.pluralize} %d - %d of %d in total} % [ - collection.offset + 1, - collection.offset + collection.length, - collection.total_entries - ] - end - end def self.total_pages_for_collection(collection) #:nodoc: if collection.respond_to?('page_count') and !collection.respond_to?('total_pages') @@ -181,196 +52,4 @@ def total_pages; page_count; end collection.total_pages end end - - # This class does the heavy lifting of actually building the pagination - # links. It is used by +will_paginate+ helper internally. - class LinkRenderer - - # The gap in page links is represented by: - # - # - attr_accessor :gap_marker - - def initialize - @gap_marker = '' - end - - # * +collection+ is a WillPaginate::Collection instance or any other object - # that conforms to that API - # * +options+ are forwarded from +will_paginate+ view helper - # * +template+ is the reference to the template being rendered - def prepare(collection, options, template) - @collection = collection - @options = options - @template = template - - # reset values in case we're re-using this instance - @total_pages = @param_name = @url_string = nil - end - - # Process it! This method returns the complete HTML string which contains - # pagination links. Feel free to subclass LinkRenderer and change this - # method as you see fit. - def to_html - links = @options[:page_links] ? windowed_links : [] - # previous/next buttons - links.unshift page_link_or_span(@collection.previous_page, 'disabled prev_page', @options[:prev_label]) - links.push page_link_or_span(@collection.next_page, 'disabled next_page', @options[:next_label]) - - html = links.join(@options[:separator]) - @options[:container] ? @template.content_tag(:div, html, html_attributes) : html - end - - # Returns the subset of +options+ this instance was initialized with that - # represent HTML attributes for the container element of pagination links. - def html_attributes - return @html_attributes if @html_attributes - @html_attributes = @options.except *(WillPaginate::ViewHelpers.pagination_options.keys - [:class]) - # pagination of Post models will have the ID of "posts_pagination" - if @options[:container] and @options[:id] === true - @html_attributes[:id] = @collection.first.class.name.underscore.pluralize + '_pagination' - end - @html_attributes - end - - protected - - # Collects link items for visible page numbers. - def windowed_links - prev = nil - - visible_page_numbers.inject [] do |links, n| - # detect gaps: - links << gap_marker if prev and n > prev + 1 - links << page_link_or_span(n, 'current') - prev = n - links - end - end - - # Calculates visible page numbers using the :inner_window and - # :outer_window options. - def visible_page_numbers - inner_window, outer_window = @options[:inner_window].to_i, @options[:outer_window].to_i - window_from = current_page - inner_window - window_to = current_page + inner_window - - # adjust lower or upper limit if other is out of bounds - if window_to > total_pages - window_from -= window_to - total_pages - window_to = total_pages - end - if window_from < 1 - window_to += 1 - window_from - window_from = 1 - window_to = total_pages if window_to > total_pages - end - - visible = (1..total_pages).to_a - left_gap = (2 + outer_window)...window_from - right_gap = (window_to + 1)...(total_pages - outer_window) - visible -= left_gap.to_a if left_gap.last - left_gap.first > 1 - visible -= right_gap.to_a if right_gap.last - right_gap.first > 1 - - visible - end - - def page_link_or_span(page, span_class, text = nil) - text ||= page.to_s - - if page and page != current_page - classnames = span_class && span_class.index(' ') && span_class.split(' ', 2).last - page_link page, text, :rel => rel_value(page), :class => classnames - else - page_span page, text, :class => span_class - end - end - - def page_link(page, text, attributes = {}) - @template.link_to text, url_for(page), attributes - end - - def page_span(page, text, attributes = {}) - @template.content_tag :span, text, attributes - end - - # Returns URL params for +page_link_or_span+, taking the current GET params - # and :params option into account. - def url_for(page) - page_one = page == 1 - unless @url_string and !page_one - @url_params = { :escape => false } - # page links should preserve GET parameters - stringified_merge @url_params, @template.params if @template.request.get? - stringified_merge @url_params, @options[:params] if @options[:params] - - if complex = param_name.index(/[^\w-]/) - page_param = (defined?(CGIMethods) ? CGIMethods : ActionController::AbstractRequest). - parse_query_parameters("#{param_name}=#{page}") - - stringified_merge @url_params, page_param - else - @url_params[param_name] = page_one ? 1 : 2 - end - - url = @template.url_for(@url_params) - return url if page_one - - if complex - @url_string = url.sub(%r!([?&]#{CGI.escape param_name}=)#{page}!, '\1@') - return url - else - @url_string = url - @url_params[param_name] = 3 - @template.url_for(@url_params).split(//).each_with_index do |char, i| - if char == '3' and url[i, 1] == '2' - @url_string[i] = '@' - break - end - end - end - end - # finally! - @url_string.sub '@', page.to_s - end - - private - - def rel_value(page) - case page - when @collection.previous_page; 'prev' + (page == 1 ? ' start' : '') - when @collection.next_page; 'next' - when 1; 'start' - end - end - - def current_page - @collection.current_page - end - - def total_pages - @total_pages ||= WillPaginate::ViewHelpers.total_pages_for_collection(@collection) - end - - def param_name - @param_name ||= @options[:param_name].to_s - end - - def stringified_merge(target, other) - other.each do |key, value| - key = key.to_s - existing = target[key] - - if value.is_a?(Hash) - target[key] = existing = {} if existing.nil? - if existing.is_a?(Hash) - stringified_merge(existing, value) - return - end - end - - target[key] = value - end - end - end end diff --git a/lib/will_paginate/view_helpers/action_view.rb b/lib/will_paginate/view_helpers/action_view.rb new file mode 100644 index 000000000..8687095c0 --- /dev/null +++ b/lib/will_paginate/view_helpers/action_view.rb @@ -0,0 +1,74 @@ +require 'will_paginate/core_ext' +require 'will_paginate/view_helpers/common' +require 'action_view' +require 'will_paginate/view_helpers/link_renderer' + +module WillPaginate + module ViewHelpers + # ActionView helpers for Rails integration + module ActionView + include WillPaginate::ViewHelpers::Common + + def will_paginate(collection = nil, options = {}) + options, collection = collection, nil if collection.is_a? Hash + unless collection or !controller + collection_name = "@#{controller.controller_name}" + collection = instance_variable_get(collection_name) + raise ArgumentError, "The #{collection_name} variable appears to be empty. Did you " + + "forget to pass the collection object for will_paginate?" unless collection + end + # early exit if there is nothing to render + return nil unless WillPaginate::ViewHelpers.total_pages_for_collection(collection) > 1 + + options = options.symbolize_keys.reverse_merge WillPaginate::ViewHelpers.pagination_options + + # get the renderer instance + renderer = case options[:renderer] + when String + options[:renderer].to_s.constantize.new + when Class + options[:renderer].new + else + options[:renderer] + end + # render HTML for pagination + renderer.prepare collection, options, self + renderer.to_html + end + + # Wrapper for rendering pagination links at both top and bottom of a block + # of content. + # + # <% paginated_section @posts do %> + #
    + # <% for post in @posts %> + #
  1. ...
  2. + # <% end %> + #
+ # <% end %> + # + # will result in: + # + # + #
    + # ... + #
+ # + # + # Arguments are passed to a will_paginate call, so the same options + # apply. Don't use the :id option; otherwise you'll finish with two + # blocks of pagination links sharing the same ID (which is invalid HTML). + def paginated_section(*args, &block) + pagination = will_paginate(*args).to_s + content = pagination + capture(&block) + pagination + concat content, block.binding + end + end + end +end + +ActionView::Base.class_eval { include WillPaginate::ViewHelpers::ActionView } + +if defined?(ActionController::Base) and ActionController::Base.respond_to? :rescue_responses + ActionController::Base.rescue_responses['WillPaginate::InvalidPage'] = :not_found +end diff --git a/lib/will_paginate/view_helpers/common.rb b/lib/will_paginate/view_helpers/common.rb new file mode 100644 index 000000000..4ff2d748f --- /dev/null +++ b/lib/will_paginate/view_helpers/common.rb @@ -0,0 +1,103 @@ +require 'will_paginate/view_helpers' + +module WillPaginate + module ViewHelpers + module Common + # Renders Digg/Flickr-style pagination for a WillPaginate::Collection + # object. Nil is returned if there is only one page in total; no point in + # rendering the pagination in that case... + # + # ==== Options + # * :class -- CSS class name for the generated DIV (default: "pagination") + # * :prev_label -- default: "« Previous" + # * :next_label -- default: "Next »" + # * :inner_window -- how many links are shown around the current page (default: 4) + # * :outer_window -- how many links are around the first and the last page (default: 1) + # * :separator -- string separator for page HTML elements (default: single space) + # * :param_name -- parameter name for page number in URLs (default: :page) + # * :params -- additional parameters when generating pagination links + # (eg. :controller => "foo", :action => nil) + # * :renderer -- class name, class or instance of a link renderer (default: + # WillPaginate::LinkRenderer) + # * :page_links -- when false, only previous/next links are rendered (default: true) + # * :container -- toggles rendering of the DIV container for pagination links, set to + # false only when you are rendering your own pagination markup (default: true) + # * :id -- HTML ID for the container (default: nil). Pass +true+ to have the ID + # automatically generated from the class name of objects in collection: for example, paginating + # ArticleComment models would yield an ID of "article_comments_pagination". + # + # All options beside listed ones are passed as HTML attributes to the container + # element for pagination links (the DIV). For example: + # + # <%= will_paginate @posts, :id => 'wp_posts' %> + # + # ... will result in: + # + # + # + # ==== Using the helper without arguments + # If the helper is called without passing in the collection object, it will + # try to read from the instance variable inferred by the controller name. + # For example, calling +will_paginate+ while the current controller is + # PostsController will result in trying to read from the @posts + # variable. Example: + # + # <%= will_paginate :id => true %> + # + # ... will result in @post collection getting paginated: + # + # + # + def will_paginate(collection, options = {}) + # early exit if there is nothing to render + return nil unless WillPaginate::ViewHelpers.total_pages_for_collection(collection) > 1 + + options = WillPaginate::ViewHelpers.pagination_options.merge(options) + + # get the renderer instance + renderer = case options[:renderer] + when String + options[:renderer].to_s.constantize.new + when Class + options[:renderer].new + else + options[:renderer] + end + # render HTML for pagination + renderer.prepare collection, options, self + renderer.to_html + end + + # Renders a helpful message with numbers of displayed vs. total entries. + # You can use this as a blueprint for your own, similar helpers. + # + # <%= page_entries_info @posts %> + # #-> Displaying posts 6 - 10 of 26 in total + # + # By default, the message will use the humanized class name of objects + # in collection: for instance, "project types" for ProjectType models. + # Override this to your liking with the :entry_name parameter: + # + # <%= page_entries_info @posts, :entry_name => 'item' %> + # #-> Displaying items 6 - 10 of 26 in total + def page_entries_info(collection, options = {}) + entry_name = options[:entry_name] || + (collection.empty?? 'entry' : collection.first.class.name.underscore.sub('_', ' ')) + + if collection.total_pages < 2 + case collection.size + when 0; "No #{entry_name.pluralize} found" + when 1; "Displaying 1 #{entry_name}" + else; "Displaying all #{collection.size} #{entry_name.pluralize}" + end + else + %{Displaying #{entry_name.pluralize} %d - %d of %d in total} % [ + collection.offset + 1, + collection.offset + collection.length, + collection.total_entries + ] + end + end + end + end +end diff --git a/lib/will_paginate/view_helpers/link_renderer.rb b/lib/will_paginate/view_helpers/link_renderer.rb new file mode 100644 index 000000000..1a2cefba4 --- /dev/null +++ b/lib/will_paginate/view_helpers/link_renderer.rb @@ -0,0 +1,152 @@ +require 'will_paginate/core_ext' +require 'will_paginate/view_helpers/link_renderer_base' + +module WillPaginate + module ViewHelpers + # This class does the heavy lifting of actually building the pagination + # links. It is used by +will_paginate+ helper internally. + class LinkRenderer < LinkRendererBase + + def initialize + @gap_marker = '' + end + + # * +collection+ is a WillPaginate::Collection instance or any other object + # that conforms to that API + # * +options+ are forwarded from +will_paginate+ view helper + # * +template+ is the reference to the template being rendered + def prepare(collection, options, template) + super(collection, options) + @template = template + # reset values in case we're re-using this instance + @url_string = nil + end + + # Process it! This method returns the complete HTML string which contains + # pagination links. Feel free to subclass LinkRenderer and change this + # method as you see fit. + def to_html + links = @options[:page_links] ? windowed_links : [] + # previous/next buttons + links.unshift page_link_or_span(@collection.previous_page, 'disabled prev_page', @options[:prev_label]) + links.push page_link_or_span(@collection.next_page, 'disabled next_page', @options[:next_label]) + + html = links.join(@options[:separator]) + @options[:container] ? @template.content_tag(:div, html, html_attributes) : html + end + + # Returns the subset of +options+ this instance was initialized with that + # represent HTML attributes for the container element of pagination links. + def html_attributes + return @html_attributes if @html_attributes + @html_attributes = @options.except *(WillPaginate::ViewHelpers.pagination_options.keys - [:class]) + # pagination of Post models will have the ID of "posts_pagination" + if @options[:container] and @options[:id] === true + @html_attributes[:id] = @collection.first.class.name.underscore.pluralize + '_pagination' + end + @html_attributes + end + + protected + + # Collects link items for visible page numbers. + def windowed_links + prev = nil + + visible_page_numbers.inject [] do |links, n| + # detect gaps: + links << gap_marker if prev and n > prev + 1 + links << page_link_or_span(n, 'current') + prev = n + links + end + end + + def page_link_or_span(page, span_class, text = nil) + text ||= page.to_s + + if page and page != current_page + classnames = span_class && span_class.index(' ') && span_class.split(' ', 2).last + page_link page, text, :rel => rel_value(page), :class => classnames + else + page_span page, text, :class => span_class + end + end + + def page_link(page, text, attributes = {}) + @template.link_to text, url_for(page), attributes + end + + def page_span(page, text, attributes = {}) + @template.content_tag :span, text, attributes + end + + # Returns URL params for +page_link_or_span+, taking the current GET params + # and :params option into account. + def url_for(page) + page_one = page == 1 + unless @url_string and !page_one + @url_params = { :escape => false } + # page links should preserve GET parameters + stringified_merge @url_params, @template.params if @template.request.get? + stringified_merge @url_params, @options[:params] if @options[:params] + + if complex = param_name.index(/[^\w-]/) + page_param = (defined?(CGIMethods) ? CGIMethods : ActionController::AbstractRequest). + parse_query_parameters("#{param_name}=#{page}") + + stringified_merge @url_params, page_param + else + @url_params[param_name] = page_one ? 1 : 2 + end + + url = @template.url_for(@url_params) + return url if page_one + + if complex + @url_string = url.sub(%r!([?&]#{CGI.escape param_name}=)#{page}!, '\1@') + return url + else + @url_string = url + @url_params[param_name] = 3 + @template.url_for(@url_params).split(//).each_with_index do |char, i| + if char == '3' and url[i, 1] == '2' + @url_string[i] = '@' + break + end + end + end + end + # finally! + @url_string.sub '@', page.to_s + end + + private + + def rel_value(page) + case page + when @collection.previous_page; 'prev' + (page == 1 ? ' start' : '') + when @collection.next_page; 'next' + when 1; 'start' + end + end + + def stringified_merge(target, other) + other.each do |key, value| + key = key.to_s + existing = target[key] + + if value.is_a?(Hash) + target[key] = existing = {} if existing.nil? + if existing.is_a?(Hash) + stringified_merge(existing, value) + return + end + end + + target[key] = value + end + end + end + end +end diff --git a/lib/will_paginate/view_helpers/link_renderer_base.rb b/lib/will_paginate/view_helpers/link_renderer_base.rb new file mode 100644 index 000000000..ae689c3c9 --- /dev/null +++ b/lib/will_paginate/view_helpers/link_renderer_base.rb @@ -0,0 +1,71 @@ +require 'will_paginate/view_helpers' + +module WillPaginate + module ViewHelpers + # This class does the heavy lifting of actually building the pagination + # links. It is used by +will_paginate+ helper internally. + class LinkRendererBase + + # The gap in page links + attr_accessor :gap_marker + + def initialize + @gap_marker = '...' + end + + # * +collection+ is a WillPaginate::Collection instance or any other object + # that conforms to that API + # * +options+ are forwarded from +will_paginate+ view helper + def prepare(collection, options) + @collection = collection + @options = options + + # reset values in case we're re-using this instance + @total_pages = @param_name = nil + end + + protected + + # Calculates visible page numbers using the :inner_window and + # :outer_window options. + def visible_page_numbers + inner_window, outer_window = @options[:inner_window].to_i, @options[:outer_window].to_i + window_from = current_page - inner_window + window_to = current_page + inner_window + + # adjust lower or upper limit if other is out of bounds + if window_to > total_pages + window_from -= window_to - total_pages + window_to = total_pages + end + if window_from < 1 + window_to += 1 - window_from + window_from = 1 + window_to = total_pages if window_to > total_pages + end + + visible = (1..total_pages).to_a + left_gap = (2 + outer_window)...window_from + right_gap = (window_to + 1)...(total_pages - outer_window) + visible -= left_gap.to_a if left_gap.last - left_gap.first > 1 + visible -= right_gap.to_a if right_gap.last - right_gap.first > 1 + + visible + end + + private + + def current_page + @collection.current_page + end + + def total_pages + @total_pages ||= WillPaginate::ViewHelpers.total_pages_for_collection(@collection) + end + + def param_name + @param_name ||= @options[:param_name].to_s + end + end + end +end diff --git a/test/lib/view_test_process.rb b/test/lib/view_test_process.rb index e4e79d571..f474c6599 100644 --- a/test/lib/view_test_process.rb +++ b/test/lib/view_test_process.rb @@ -1,8 +1,7 @@ require 'action_controller' require 'action_controller/test_process' -require 'will_paginate' -WillPaginate.enable_actionpack +require 'will_paginate/view_helpers/action_view' ActionController::Routing::Routes.draw do |map| map.connect 'dummy/page/:page', :controller => 'dummy' diff --git a/test/view_test.rb b/test/view_test.rb index ebde9ff47..e24c9b6c8 100644 --- a/test/view_test.rb +++ b/test/view_test.rb @@ -1,7 +1,7 @@ require 'helper' require 'lib/view_test_process' -class AdditionalLinkAttributesRenderer < WillPaginate::LinkRenderer +class AdditionalLinkAttributesRenderer < WillPaginate::ViewHelpers::LinkRenderer def initialize(link_attributes = nil) super() @additional_link_attributes = link_attributes || { :default => 'true' } @@ -61,7 +61,7 @@ def test_will_paginate_using_renderer_class end def test_will_paginate_using_renderer_instance - renderer = WillPaginate::LinkRenderer.new + renderer = WillPaginate::ViewHelpers::LinkRenderer.new renderer.gap_marker = '~~' paginate({ :per_page => 2 }, :inner_window => 0, :outer_window => 0, :renderer => renderer) do From ec4ad61f7a443a0d7f3ab84820b0933c9a5c8799 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mislav=20Marohni=C4=87?= Date: Fri, 9 May 2008 06:58:48 +0200 Subject: [PATCH 008/168] ActionView helpers should rely on Common more --- lib/will_paginate.rb | 1 + lib/will_paginate/view_helpers/action_view.rb | 19 ++----------------- 2 files changed, 3 insertions(+), 17 deletions(-) diff --git a/lib/will_paginate.rb b/lib/will_paginate.rb index b27f9ec32..77304cb8d 100644 --- a/lib/will_paginate.rb +++ b/lib/will_paginate.rb @@ -10,6 +10,7 @@ module WillPaginate # no-op def self.enable + Deprecation.warn "WillPaginate::enable() doesn't do anything anymore" end # Enable named_scope, a feature of Rails 2.1, even if you have older Rails diff --git a/lib/will_paginate/view_helpers/action_view.rb b/lib/will_paginate/view_helpers/action_view.rb index 8687095c0..ceb97e08e 100644 --- a/lib/will_paginate/view_helpers/action_view.rb +++ b/lib/will_paginate/view_helpers/action_view.rb @@ -17,23 +17,8 @@ def will_paginate(collection = nil, options = {}) raise ArgumentError, "The #{collection_name} variable appears to be empty. Did you " + "forget to pass the collection object for will_paginate?" unless collection end - # early exit if there is nothing to render - return nil unless WillPaginate::ViewHelpers.total_pages_for_collection(collection) > 1 - - options = options.symbolize_keys.reverse_merge WillPaginate::ViewHelpers.pagination_options - - # get the renderer instance - renderer = case options[:renderer] - when String - options[:renderer].to_s.constantize.new - when Class - options[:renderer].new - else - options[:renderer] - end - # render HTML for pagination - renderer.prepare collection, options, self - renderer.to_html + + super(collection, options.symbolize_keys) end # Wrapper for rendering pagination links at both top and bottom of a block From 42c8e31fde4c554a56a99614dbd834c5c1da57ca Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mislav=20Marohni=C4=87?= Date: Fri, 9 May 2008 07:39:51 +0200 Subject: [PATCH 009/168] remove ActiveSupport dependency from Finders::Common, add some specs for it --- lib/will_paginate/finders/common.rb | 7 +-- spec/finders_spec.rb | 67 +++++++++++++++++++++++++++++ test/finder_test.rb | 26 ----------- 3 files changed, 71 insertions(+), 29 deletions(-) create mode 100644 spec/finders_spec.rb diff --git a/lib/will_paginate/finders/common.rb b/lib/will_paginate/finders/common.rb index 1551408c7..d50146f89 100644 --- a/lib/will_paginate/finders/common.rb +++ b/lib/will_paginate/finders/common.rb @@ -56,8 +56,8 @@ def paginated_each(options = {}, &block) protected def wp_parse_options(options) #:nodoc: - raise ArgumentError, 'parameter hash expected' unless options.respond_to? :symbolize_keys - options = options.symbolize_keys + raise ArgumentError, 'parameter hash expected' unless Hash === options + # options = options.symbolize_keys raise ArgumentError, ':page parameter required' unless options.key? :page if options[:count] and options[:total_entries] @@ -67,7 +67,8 @@ def wp_parse_options(options) #:nodoc: page = options[:page] || 1 per_page = options[:per_page] || self.per_page total = options[:total_entries] - [page, per_page, total] + + return [page, per_page, total] end end diff --git a/spec/finders_spec.rb b/spec/finders_spec.rb new file mode 100644 index 000000000..2412ceaa9 --- /dev/null +++ b/spec/finders_spec.rb @@ -0,0 +1,67 @@ +require 'spec_helper' +require 'will_paginate/finders/common' + +class Model + extend WillPaginate::Finders::Common +end + +describe WillPaginate::Finders::Common do + it "should define default per_page of 30" do + Model.per_page.should == 30 + end + + it "should result with WillPaginate::Collection" do + Model.expects(:wp_query) + Model.paginate(:page => nil).should be_instance_of(WillPaginate::Collection) + end + + it "should delegate pagination to wp_query" do + Model.expects(:wp_query).with({}, instance_of(WillPaginate::Collection), []) + Model.paginate :page => nil + end + + it "should complain when no hash parameters given" do + Proc.new { + Model.paginate + }.should raise_error(ArgumentError, 'parameter hash expected') + end + + it "should complain when no :page parameter present" do + Proc.new { + Model.paginate :per_page => 6 + }.should raise_error(ArgumentError, ':page parameter required') + end + + it "should complain when both :count and :total_entries are given" do + Proc.new { + Model.paginate :page => 1, :count => {}, :total_entries => 1 + }.should raise_error(ArgumentError, ':count and :total_entries are mutually exclusive') + end + + it "should never mangle options" do + options = { :page => 1 } + options.expects(:delete).never + options_before = options.dup + + Model.expects(:wp_query) + Model.paginate(options) + + options.should == options_before + end + + it "should provide paginated_each functionality" do + collection = stub('collection', :size => 5, :empty? => false, :per_page => 5) + collection.expects(:each).times(2).returns(collection) + last_collection = stub('collection', :size => 4, :empty? => false, :per_page => 5) + last_collection.expects(:each).returns(last_collection) + + params = { :order => 'id', :total_entries => 0 } + + Model.expects(:paginate).with(params.merge(:page => 2)).returns(collection) + Model.expects(:paginate).with(params.merge(:page => 3)).returns(collection) + Model.expects(:paginate).with(params.merge(:page => 4)).returns(last_collection) + + total = Model.paginated_each(:page => '2') { } + total.should == 14 + end +end diff --git a/test/finder_test.rb b/test/finder_test.rb index 19581b2f9..4fe7ef178 100644 --- a/test/finder_test.rb +++ b/test/finder_test.rb @@ -28,10 +28,6 @@ def test_simple_paginate end def test_parameter_api - # :page parameter in options is required! - assert_raise(ArgumentError){ Topic.paginate } - assert_raise(ArgumentError){ Topic.paginate({}) } - # explicit :all should not break anything assert_equal Topic.paginate(:page => nil), Topic.paginate(:all, :page => 1) @@ -263,13 +259,6 @@ def test_paginate_in_named_scope_on_has_many_association end ## misc ## - - def test_count_and_total_entries_options_are_mutually_exclusive - e = assert_raise ArgumentError do - Developer.paginate :page => 1, :count => {}, :total_entries => 1 - end - assert_match /exclusive/, e.to_s - end def test_readonly assert_nothing_raised { Developer.paginate :readonly => true, :page => 1 } @@ -397,20 +386,5 @@ def test_paginating_finder_doesnt_mangle_options Developer.paginate(options) assert_equal options, options_before end - - def test_paginated_each - collection = stub('collection', :size => 5, :empty? => false, :per_page => 5) - collection.expects(:each).times(2).returns(collection) - last_collection = stub('collection', :size => 4, :empty? => false, :per_page => 5) - last_collection.expects(:each).returns(last_collection) - - params = { :order => 'id', :total_entries => 0 } - - Developer.expects(:paginate).with(params.merge(:page => 2)).returns(collection) - Developer.expects(:paginate).with(params.merge(:page => 3)).returns(collection) - Developer.expects(:paginate).with(params.merge(:page => 4)).returns(last_collection) - - assert_equal 14, Developer.paginated_each(:page => '2') { } - end end end From ad66001d7f816ddfcdaf24e75c0fd1fd1dfc464a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mislav=20Marohni=C4=87?= Date: Fri, 9 May 2008 11:48:50 +0200 Subject: [PATCH 010/168] specs for common view helpers --- lib/will_paginate/core_ext.rb | 24 ++++++++++ lib/will_paginate/view_helpers/common.rb | 40 +++++++++++++--- spec/spec_helper.rb | 27 +++++++++++ spec/view_helpers/common_spec.rb | 60 ++++++++++++++++++++++++ test/view_test.rb | 53 --------------------- 5 files changed, 145 insertions(+), 59 deletions(-) create mode 100644 spec/view_helpers/common_spec.rb diff --git a/lib/will_paginate/core_ext.rb b/lib/will_paginate/core_ext.rb index 32f10f502..c7564c814 100644 --- a/lib/will_paginate/core_ext.rb +++ b/lib/will_paginate/core_ext.rb @@ -30,3 +30,27 @@ def slice!(*keys) end end end + +unless String.instance_methods.include? 'constantize' + String.class_eval do + def constantize + unless /\A(?:::)?([A-Z]\w*(?:::[A-Z]\w*)*)\z/ =~ self + raise NameError, "#{self.inspect} is not a valid constant name!" + end + + Object.module_eval("::#{$1}", __FILE__, __LINE__) + end + end +end + +unless String.instance_methods.include? 'underscore' + String.class_eval do + def underscore + self.to_s.gsub(/::/, '/'). + gsub(/([A-Z]+)([A-Z][a-z])/,'\1_\2'). + gsub(/([a-z\d])([A-Z])/,'\1_\2'). + tr("-", "_"). + downcase + end + end +end diff --git a/lib/will_paginate/view_helpers/common.rb b/lib/will_paginate/view_helpers/common.rb index 4ff2d748f..2506aabb6 100644 --- a/lib/will_paginate/view_helpers/common.rb +++ b/lib/will_paginate/view_helpers/common.rb @@ -80,18 +80,46 @@ def will_paginate(collection, options = {}) # # <%= page_entries_info @posts, :entry_name => 'item' %> # #-> Displaying items 6 - 10 of 26 in total + # + # Entry name is entered in singular and pluralized with + # String#pluralize method from ActiveSupport. If it isn't + # loaded, specify plural with :plural_name parameter: + # + # <%= page_entries_info @posts, :entry_name => 'item', :plural_name => 'items' %> + # + # By default, this method produces HTML output. You can trigger plain + # text output by passing :html => false in options. def page_entries_info(collection, options = {}) - entry_name = options[:entry_name] || - (collection.empty?? 'entry' : collection.first.class.name.underscore.sub('_', ' ')) + entry_name = options[:entry_name] || (collection.empty?? 'entry' : + collection.first.class.name.underscore.gsub('_', ' ')) + + plural_name = if options[:plural_name] + options[:plural_name] + elsif entry_name == 'entry' + plural_name = 'entries' + elsif entry_name.respond_to? :pluralize + plural_name = entry_name.pluralize + else + entry_name + 's' + end + + unless options[:html] == false + b = '' + eb = '' + sp = ' ' + else + b = eb = '' + sp = ' ' + end if collection.total_pages < 2 case collection.size - when 0; "No #{entry_name.pluralize} found" - when 1; "Displaying 1 #{entry_name}" - else; "Displaying all #{collection.size} #{entry_name.pluralize}" + when 0; "No #{plural_name} found" + when 1; "Displaying #{b}1#{eb} #{entry_name}" + else; "Displaying #{b}all #{collection.size}#{eb} #{plural_name}" end else - %{Displaying #{entry_name.pluralize} %d - %d of %d in total} % [ + %{Displaying #{plural_name} #{b}%d#{sp}-#{sp}%d#{eb} of #{b}%d#{eb} in total} % [ collection.offset + 1, collection.offset + collection.length, collection.total_entries diff --git a/spec/spec_helper.rb b/spec/spec_helper.rb index b16f15342..fee4de62e 100644 --- a/spec/spec_helper.rb +++ b/spec/spec_helper.rb @@ -2,9 +2,36 @@ gem 'rspec', '~> 1.1.3' require 'spec' +module StringMatchers + def include_words(string) + WordsInclusionMatcher.new(string) + end +end + Spec::Runner.configure do |config| # config.include My::Pony, My::Horse, :type => :farm + config.include StringMatchers # config.predicate_matchers[:swim] = :can_swim? config.mock_with :mocha end + +class WordsInclusionMatcher + def initialize(string) + @string = string + @pattern = /\b#{string}\b/ + end + + def matches?(actual) + @actual = actual.to_s + @actual =~ @pattern + end + + def failure_message + "expected #{@actual.inspect} to contain words #{@string.inspect}" + end + + def negative_failure_message + "expected #{@actual.inspect} not to contain words #{@string.inspect}" + end +end diff --git a/spec/view_helpers/common_spec.rb b/spec/view_helpers/common_spec.rb new file mode 100644 index 000000000..f200bcd0e --- /dev/null +++ b/spec/view_helpers/common_spec.rb @@ -0,0 +1,60 @@ +require 'spec_helper' +require 'will_paginate/view_helpers/common' +require 'will_paginate/array' + +describe WillPaginate::ViewHelpers::Common do + + include WillPaginate::ViewHelpers::Common + + describe "will_paginate" do + it "should render" do + collection = WillPaginate::Collection.new(1, 2, 4) + will_paginate(collection).should_not be_nil + end + + it "should return nil for single-page collections" do + collection = mock 'Collection', :total_pages => 1 + will_paginate(collection).should be_nil + end + end + + describe "page_entries_info" do + before :all do + @array = ('a'..'z').to_a + end + + def info(params, options = {}) + options[:html] ||= false unless options.key?(:html) and options[:html].nil? + collection = Hash === params ? @array.paginate(params) : params + page_entries_info collection, options + end + + it "should display middle results and total count" do + info(:page => 2, :per_page => 5).should == "Displaying strings 6 - 10 of 26 in total" + end + + it "should output HTML by default" do + info({ :page => 2, :per_page => 5 }, :html => nil).should == + "Displaying strings 6 - 10 of 26 in total" + end + + it "should display shortened end results" do + info(:page => 7, :per_page => 4).should include_words('strings 25 - 26') + end + + it "should handle longer class names" do + collection = @array.paginate(:page => 2, :per_page => 5) + collection.first.stubs(:class).returns(mock('Class', :name => 'ProjectType')) + info(collection).should include_words('project types') + end + + it "should adjust output for single-page collections" do + info(('a'..'d').to_a.paginate(:page => 1, :per_page => 5)).should == "Displaying all 4 strings" + info(['a'].paginate(:page => 1, :per_page => 5)).should == "Displaying 1 string" + end + + it "should display 'no entries found' for empty collections" do + info([].paginate(:page => 1, :per_page => 5)).should == "No entries found" + end + end +end diff --git a/test/view_test.rb b/test/view_test.rb index e24c9b6c8..f015436f7 100644 --- a/test/view_test.rb +++ b/test/view_test.rb @@ -160,59 +160,6 @@ def test_paginated_section assert_select 'div.pagination', 2 assert_select 'div.pagination + div#developers', 1 end - - def test_page_entries_info - @template = '<%= page_entries_info collection %>' - array = ('a'..'z').to_a - - paginate array.paginate(:page => 2, :per_page => 5) - assert_equal %{Displaying strings 6 - 10 of 26 in total}, - @html_result - - paginate array.paginate(:page => 7, :per_page => 4) - assert_equal %{Displaying strings 25 - 26 of 26 in total}, - @html_result - end - - def test_page_entries_info_with_longer_class_name - @template = '<%= page_entries_info collection %>' - collection = ('a'..'z').to_a.paginate - collection.first.stubs(:class).returns(mock('class', :name => 'ProjectType')) - - paginate collection - assert @html_result.index('project types'), "expected <#{@html_result.inspect}> to mention 'project types'" - end - - def test_page_entries_info_with_single_page_collection - @template = '<%= page_entries_info collection %>' - - paginate(('a'..'d').to_a.paginate(:page => 1, :per_page => 5)) - assert_equal %{Displaying all 4 strings}, @html_result - - paginate(['a'].paginate(:page => 1, :per_page => 5)) - assert_equal %{Displaying 1 string}, @html_result - - paginate([].paginate(:page => 1, :per_page => 5)) - assert_equal %{No entries found}, @html_result - end - - def test_page_entries_info_with_custom_entry_name - @template = '<%= page_entries_info collection, :entry_name => "author" %>' - - entries = (1..20).to_a - - paginate(entries.paginate(:page => 1, :per_page => 5)) - assert_equal %{Displaying authors 1 - 5 of 20 in total}, @html_result - - paginate(entries.paginate(:page => 1, :per_page => 20)) - assert_equal %{Displaying all 20 authors}, @html_result - - paginate(['a'].paginate(:page => 1, :per_page => 5)) - assert_equal %{Displaying 1 author}, @html_result - - paginate([].paginate(:page => 1, :per_page => 5)) - assert_equal %{No authors found}, @html_result - end ## parameter handling in page links ## From c71ca99e4884da1da782811dcb8f43382326fd6d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mislav=20Marohni=C4=87?= Date: Fri, 9 May 2008 12:06:08 +0200 Subject: [PATCH 011/168] fix spec for will_paginate in ViewHelpers::Common --- lib/will_paginate/core_ext.rb | 2 ++ lib/will_paginate/view_helpers/common.rb | 2 +- spec/view_helpers/common_spec.rb | 6 +++++- 3 files changed, 8 insertions(+), 2 deletions(-) diff --git a/lib/will_paginate/core_ext.rb b/lib/will_paginate/core_ext.rb index c7564c814..4601f005a 100644 --- a/lib/will_paginate/core_ext.rb +++ b/lib/will_paginate/core_ext.rb @@ -1,6 +1,8 @@ require 'set' require 'will_paginate/array' +## Everything below blatantly stolen from ActiveSupport :o + unless Hash.instance_methods.include? 'except' Hash.class_eval do # Returns a new hash without the given keys. diff --git a/lib/will_paginate/view_helpers/common.rb b/lib/will_paginate/view_helpers/common.rb index 2506aabb6..588d9800f 100644 --- a/lib/will_paginate/view_helpers/common.rb +++ b/lib/will_paginate/view_helpers/common.rb @@ -57,7 +57,7 @@ def will_paginate(collection, options = {}) # get the renderer instance renderer = case options[:renderer] when String - options[:renderer].to_s.constantize.new + options[:renderer].constantize.new when Class options[:renderer].new else diff --git a/spec/view_helpers/common_spec.rb b/spec/view_helpers/common_spec.rb index f200bcd0e..c3ddf695f 100644 --- a/spec/view_helpers/common_spec.rb +++ b/spec/view_helpers/common_spec.rb @@ -9,7 +9,11 @@ describe "will_paginate" do it "should render" do collection = WillPaginate::Collection.new(1, 2, 4) - will_paginate(collection).should_not be_nil + renderer = mock 'Renderer' + renderer.expects(:prepare).with(collection, instance_of(Hash), self) + renderer.expects(:to_html).returns('') + + will_paginate(collection, :renderer => renderer).should == '' end it "should return nil for single-page collections" do From 16faca8a3e5ab245e389cdd16a9b45bc229eeeaf Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mislav=20Marohni=C4=87?= Date: Sat, 17 May 2008 07:45:56 +0200 Subject: [PATCH 012/168] ViewHelpers::Common -> ViewHelpers::Base --- lib/will_paginate/view_helpers/{common.rb => base.rb} | 2 +- spec/view_helpers/{common_spec.rb => base_spec.rb} | 6 +++--- 2 files changed, 4 insertions(+), 4 deletions(-) rename lib/will_paginate/view_helpers/{common.rb => base.rb} (99%) rename spec/view_helpers/{common_spec.rb => base_spec.rb} (94%) diff --git a/lib/will_paginate/view_helpers/common.rb b/lib/will_paginate/view_helpers/base.rb similarity index 99% rename from lib/will_paginate/view_helpers/common.rb rename to lib/will_paginate/view_helpers/base.rb index 588d9800f..cb4d8c6d8 100644 --- a/lib/will_paginate/view_helpers/common.rb +++ b/lib/will_paginate/view_helpers/base.rb @@ -2,7 +2,7 @@ module WillPaginate module ViewHelpers - module Common + module Base # Renders Digg/Flickr-style pagination for a WillPaginate::Collection # object. Nil is returned if there is only one page in total; no point in # rendering the pagination in that case... diff --git a/spec/view_helpers/common_spec.rb b/spec/view_helpers/base_spec.rb similarity index 94% rename from spec/view_helpers/common_spec.rb rename to spec/view_helpers/base_spec.rb index c3ddf695f..399aee5b7 100644 --- a/spec/view_helpers/common_spec.rb +++ b/spec/view_helpers/base_spec.rb @@ -1,10 +1,10 @@ require 'spec_helper' -require 'will_paginate/view_helpers/common' +require 'will_paginate/view_helpers/base' require 'will_paginate/array' -describe WillPaginate::ViewHelpers::Common do +describe WillPaginate::ViewHelpers::Base do - include WillPaginate::ViewHelpers::Common + include WillPaginate::ViewHelpers::Base describe "will_paginate" do it "should render" do From 242ab68ea2e6a875bde41fe937e1863dc4d80634 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mislav=20Marohni=C4=87?= Date: Sat, 17 May 2008 08:11:39 +0200 Subject: [PATCH 013/168] LinkRendererBase initial spec --- spec/spec_helper.rb | 13 +++++++++++-- spec/view_helpers/link_renderer_base_spec.rb | 20 ++++++++++++++++++++ 2 files changed, 31 insertions(+), 2 deletions(-) create mode 100644 spec/view_helpers/link_renderer_base_spec.rb diff --git a/spec/spec_helper.rb b/spec/spec_helper.rb index fee4de62e..2c676773d 100644 --- a/spec/spec_helper.rb +++ b/spec/spec_helper.rb @@ -2,15 +2,24 @@ gem 'rspec', '~> 1.1.3' require 'spec' -module StringMatchers +module MyExtras + protected def include_words(string) WordsInclusionMatcher.new(string) end + + def collection(params = {}) + if params[:total_pages] + params[:per_page] = 1 + params[:total_entries] = params[:total_pages] + end + WillPaginate::Collection.new(params[:page] || 1, params[:per_page] || 30, params[:total_entries]) + end end Spec::Runner.configure do |config| # config.include My::Pony, My::Horse, :type => :farm - config.include StringMatchers + config.include MyExtras # config.predicate_matchers[:swim] = :can_swim? config.mock_with :mocha diff --git a/spec/view_helpers/link_renderer_base_spec.rb b/spec/view_helpers/link_renderer_base_spec.rb new file mode 100644 index 000000000..ce16f93ae --- /dev/null +++ b/spec/view_helpers/link_renderer_base_spec.rb @@ -0,0 +1,20 @@ +require 'spec_helper' +require 'will_paginate/view_helpers/link_renderer_base' + +describe WillPaginate::ViewHelpers::LinkRendererBase do + it "should have gap marked initialized" do + @renderer = create + @renderer.gap_marker.should == '...' + end + + it "should prepare with collection and options" do + @renderer = create + @renderer.prepare(collection, { :param_name => 'mypage' }) + @renderer.send(:current_page).should == 1 + @renderer.send(:param_name).should == 'mypage' + end + + def create + WillPaginate::ViewHelpers::LinkRendererBase.new + end +end From d767a35ff4c549f44afda847f89d01fbcbf5dda0 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mislav=20Marohni=C4=87?= Date: Fri, 30 May 2008 02:48:34 +0200 Subject: [PATCH 014/168] initial ActiveResource support --- lib/will_paginate/finders/active_resource.rb | 48 ++++++++++++++++++ spec/finders/active_resource_spec.rb | 52 ++++++++++++++++++++ spec/finders_spec.rb | 6 +-- spec/spec_helper.rb | 2 +- 4 files changed, 104 insertions(+), 4 deletions(-) create mode 100644 lib/will_paginate/finders/active_resource.rb create mode 100644 spec/finders/active_resource_spec.rb diff --git a/lib/will_paginate/finders/active_resource.rb b/lib/will_paginate/finders/active_resource.rb new file mode 100644 index 000000000..4f1014b03 --- /dev/null +++ b/lib/will_paginate/finders/active_resource.rb @@ -0,0 +1,48 @@ +require 'will_paginate/finders/common' +require 'active_resource' + +module WillPaginate::Finders + # Paginate your ActiveResource models. + # + # @posts = Post.paginate :all, :params => { :page => params[:page], :order => 'created_at DESC' } + module ActiveResource + include WillPaginate::Finders::Common + + protected + + def wp_query(options, pager, args, &block) + unless args.empty? or args.first == :all + raise ArgumentError, "finder arguments other than :all are not supported for pagination (#{args.inspect} given)" + end + params = (options[:params] ||= {}) + params[:page] = pager.current_page + params[:per_page] = pager.per_page + + pager.replace find_every(options, &block) + end + + # Takes the format that Hash.from_xml produces out of an unknown type + # (produced by WillPaginate::Collection#to_xml_with_collection_type), + # parses it into a WillPaginate::Collection, + # and forwards the result to the former +instantiate_collection+ method. + # It only does this for hashes that have a :type => "collection". + def instantiate_collection_with_collection(collection, prefix_options = {}) + if collection.is_a?(Hash) && collection["type"] == "collection" + collectables = collection.values.find{ |c| c.is_a?(Hash) || c.is_a?(Array) } + collectables = [collectables].compact unless collectables.kind_of?(Array) + instantiated_collection = WillPaginate::Collection.create(collection["current_page"], collection["per_page"], collection["total_entries"]) do |pager| + pager.replace instantiate_collection_without_collection(collectables, prefix_options) + end + else + instantiate_collection_without_collection(collection, prefix_options) + end + end + end +end + +ActiveResource::Base.class_eval do + extend WillPaginate::Finders::ActiveResource + class << self + # alias_method_chain :instantiate_collection, :collection + end +end \ No newline at end of file diff --git a/spec/finders/active_resource_spec.rb b/spec/finders/active_resource_spec.rb new file mode 100644 index 000000000..e00bb12b3 --- /dev/null +++ b/spec/finders/active_resource_spec.rb @@ -0,0 +1,52 @@ +require 'spec_helper' +require 'will_paginate/finders/active_resource' +require 'active_resource/http_mock' + +class AresProject < ActiveResource::Base + self.site = 'http://localhost:4000' +end + +describe WillPaginate::Finders::ActiveResource do + + before :all do + # ActiveResource::HttpMock.respond_to do |mock| + # mock.get "/ares_projects.xml?page=1&per_page=5", {}, [].to_xml + # end + end + + it "should integrate with ActiveResource::Base" do + ActiveResource::Base.should respond_to(:paginate) + end + + it "should error when no parameters for #paginate" do + lambda { AresProject.paginate }.should raise_error(ArgumentError) + end + + it "should paginate" do + AresProject.expects(:find_every).with(:params => { :page => 1, :per_page => 5 }).returns([]) + AresProject.paginate(:page => 1, :per_page => 5) + end + + it "should have 30 per_page as default" do + AresProject.expects(:find_every).with(:params => { :page => 1, :per_page => 30 }).returns([]) + AresProject.paginate(:page => 1) + end + + it "should support #paginate(:all)" do + lambda { AresProject.paginate(:all) }.should raise_error(ArgumentError) + end + + it "should error #paginate(:other)" do + lambda { AresProject.paginate(:first) }.should raise_error(ArgumentError) + end + + protected + + def create(page = 2, limit = 5, total = nil, &block) + if block_given? + WillPaginate::Collection.create(page, limit, total, &block) + else + WillPaginate::Collection.new(page, limit, total) + end + end +end diff --git a/spec/finders_spec.rb b/spec/finders_spec.rb index 2412ceaa9..57ef69e2e 100644 --- a/spec/finders_spec.rb +++ b/spec/finders_spec.rb @@ -21,19 +21,19 @@ class Model end it "should complain when no hash parameters given" do - Proc.new { + lambda { Model.paginate }.should raise_error(ArgumentError, 'parameter hash expected') end it "should complain when no :page parameter present" do - Proc.new { + lambda { Model.paginate :per_page => 6 }.should raise_error(ArgumentError, ':page parameter required') end it "should complain when both :count and :total_entries are given" do - Proc.new { + lambda { Model.paginate :page => 1, :count => {}, :total_entries => 1 }.should raise_error(ArgumentError, ':count and :total_entries are mutually exclusive') end diff --git a/spec/spec_helper.rb b/spec/spec_helper.rb index 2c676773d..be5e918ed 100644 --- a/spec/spec_helper.rb +++ b/spec/spec_helper.rb @@ -1,5 +1,5 @@ require 'rubygems' -gem 'rspec', '~> 1.1.3' +gem 'rspec', '~> 1.1.4' require 'spec' module MyExtras From 04348cfece8ebf04e4f331ba68157c47f10a370c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mislav=20Marohni=C4=87?= Date: Fri, 30 May 2008 04:00:49 +0200 Subject: [PATCH 015/168] fixture-independent specs in active_record_spec --- {test => spec}/database.yml | 0 spec/finders/active_record_spec.rb | 138 ++++++++++++++++++ .../finders}/activerecord_test_connector.rb | 2 +- {test => spec}/fixtures/admin.rb | 0 {test => spec}/fixtures/developer.rb | 0 .../fixtures/developers_projects.yml | 0 {test => spec}/fixtures/project.rb | 0 {test => spec}/fixtures/projects.yml | 0 {test => spec}/fixtures/replies.yml | 0 {test => spec}/fixtures/reply.rb | 0 {test => spec}/fixtures/schema.rb | 0 {test => spec}/fixtures/topic.rb | 0 {test => spec}/fixtures/topics.yml | 0 {test => spec}/fixtures/user.rb | 0 {test => spec}/fixtures/users.yml | 0 test/finder_test.rb | 129 ---------------- 16 files changed, 139 insertions(+), 130 deletions(-) rename {test => spec}/database.yml (100%) create mode 100644 spec/finders/active_record_spec.rb rename {test/lib => spec/finders}/activerecord_test_connector.rb (98%) rename {test => spec}/fixtures/admin.rb (100%) rename {test => spec}/fixtures/developer.rb (100%) rename {test => spec}/fixtures/developers_projects.yml (100%) rename {test => spec}/fixtures/project.rb (100%) rename {test => spec}/fixtures/projects.yml (100%) rename {test => spec}/fixtures/replies.yml (100%) rename {test => spec}/fixtures/reply.rb (100%) rename {test => spec}/fixtures/schema.rb (100%) rename {test => spec}/fixtures/topic.rb (100%) rename {test => spec}/fixtures/topics.yml (100%) rename {test => spec}/fixtures/user.rb (100%) rename {test => spec}/fixtures/users.yml (100%) diff --git a/test/database.yml b/spec/database.yml similarity index 100% rename from test/database.yml rename to spec/database.yml diff --git a/spec/finders/active_record_spec.rb b/spec/finders/active_record_spec.rb new file mode 100644 index 000000000..c9b01213f --- /dev/null +++ b/spec/finders/active_record_spec.rb @@ -0,0 +1,138 @@ +require 'spec_helper' +require 'will_paginate/finders/active_record' +require File.dirname(__FILE__) + '/activerecord_test_connector' + +class ArProject < ActiveRecord::Base +end + +ActiverecordTestConnector.setup + +describe WillPaginate::Finders::ActiveRecord do + + before :all do + # Fixtures.create_fixtures ActiverecordTestConnector::FIXTURES_PATH, %w() + end + + it "should integrate with ActiveRecord::Base" do + ActiveRecord::Base.should respond_to(:paginate) + end + + it "should paginate" do + ArProject.expects(:find).with(:all, { :limit => 5, :offset => 0 }).returns([]) + ArProject.paginate(:page => 1, :per_page => 5) + end + + it "should respond to paginate_by_sql" do + ArProject.should respond_to(:paginate_by_sql) + end + + it "should support explicit :all argument" do + ArProject.expects(:find).with(:all, instance_of(Hash)).returns([]) + ArProject.paginate(:all, :page => nil) + end + + it "should put implicit all in dynamic finders" do + ArProject.expects(:find_all_by_foo).returns([]) + ArProject.expects(:count).returns(0) + ArProject.paginate_by_foo :page => 2 + end + + it "should leave extra parameters intact" do + ArProject.expects(:find).with(:all, {:foo => 'bar', :limit => 4, :offset => 0 }).returns(Array.new(5)) + ArProject.expects(:count).with({:foo => 'bar'}).returns(1) + + ArProject.paginate :foo => 'bar', :page => 1, :per_page => 4 + end + + describe "counting" do + it "should ignore nil in :count parameter" do + ArProject.expects(:find).returns([]) + lambda { ArProject.paginate :page => nil, :count => nil }.should_not raise_error + end + + it "should guess the total count" do + ArProject.expects(:find).returns(Array.new(2)) + ArProject.expects(:count).never + + result = ArProject.paginate :page => 2, :per_page => 4 + result.total_entries.should == 6 + end + + it "should guess that there are no records" do + ArProject.expects(:find).returns([]) + ArProject.expects(:count).never + + result = ArProject.paginate :page => 1, :per_page => 4 + result.total_entries.should == 0 + end + end + + it "should not ignore :select parameter when it says DISTINCT" do + ArProject.stubs(:find).returns([]) + ArProject.expects(:count).with(:select => 'DISTINCT salary').returns(0) + ArProject.paginate :select => 'DISTINCT salary', :page => 2 + end + + it "should use :with_foo for scope-out compatibility" do + ArProject.expects(:find_best).returns(Array.new(5)) + ArProject.expects(:with_best).returns(1) + + ArProject.paginate_best :page => 1, :per_page => 4 + end + + describe "paginate_by_sql" do + it "should paginate" do + ArProject.expects(:find_by_sql).with(regexp_matches(/sql LIMIT 3(,| OFFSET) 3/)).returns([]) + ArProject.expects(:count_by_sql).with('SELECT COUNT(*) FROM (sql) AS count_table').returns(0) + + ArProject.paginate_by_sql 'sql', :page => 2, :per_page => 3 + end + + it "should respect total_entrier setting" do + ArProject.expects(:find_by_sql).returns([]) + ArProject.expects(:count_by_sql).never + + entries = ArProject.paginate_by_sql 'sql', :page => 1, :total_entries => 999 + entries.total_entries.should == 999 + end + + it "should strip the order when counting" do + ArProject.expects(:find_by_sql).returns([]) + ArProject.expects(:count_by_sql).with("SELECT COUNT(*) FROM (sql\n ) AS count_table").returns(0) + + ArProject.paginate_by_sql "sql\n ORDER\nby foo, bar, `baz` ASC", :page => 2 + end + end + + # TODO: counts would still be wrong! + it "should be able to paginate custom finders" do + # acts_as_taggable defines find_tagged_with(tag, options) + ArProject.expects(:find_tagged_with).with('will_paginate', :offset => 5, :limit => 5).returns([]) + ArProject.expects(:count).with({}).returns(0) + + ArProject.paginate_tagged_with 'will_paginate', :page => 2, :per_page => 5 + end + + it "should not skip count when given an array argument to a finder" do + ids = (1..8).to_a + ArProject.expects(:find_all_by_id).returns([]) + ArProject.expects(:count).returns(0) + + ArProject.paginate_by_id(ids, :per_page => 3, :page => 2, :order => 'id') + end + + it "doesn't mangle options" do + ArProject.expects(:find).returns([]) + options = { :page => 1 } + options.expects(:delete).never + options_before = options.dup + + ArProject.paginate(options) + options.should == options_before + end + + if ActiverecordTestConnector.able_to_connect + # fixture-dependent tests here + end + +end diff --git a/test/lib/activerecord_test_connector.rb b/spec/finders/activerecord_test_connector.rb similarity index 98% rename from test/lib/activerecord_test_connector.rb rename to spec/finders/activerecord_test_connector.rb index 0decd8a2f..615891e7a 100644 --- a/test/lib/activerecord_test_connector.rb +++ b/spec/finders/activerecord_test_connector.rb @@ -2,7 +2,7 @@ require 'active_record/version' require 'active_record/fixtures' -class ActiveRecordTestConnector +class ActiverecordTestConnector cattr_accessor :able_to_connect cattr_accessor :connected diff --git a/test/fixtures/admin.rb b/spec/fixtures/admin.rb similarity index 100% rename from test/fixtures/admin.rb rename to spec/fixtures/admin.rb diff --git a/test/fixtures/developer.rb b/spec/fixtures/developer.rb similarity index 100% rename from test/fixtures/developer.rb rename to spec/fixtures/developer.rb diff --git a/test/fixtures/developers_projects.yml b/spec/fixtures/developers_projects.yml similarity index 100% rename from test/fixtures/developers_projects.yml rename to spec/fixtures/developers_projects.yml diff --git a/test/fixtures/project.rb b/spec/fixtures/project.rb similarity index 100% rename from test/fixtures/project.rb rename to spec/fixtures/project.rb diff --git a/test/fixtures/projects.yml b/spec/fixtures/projects.yml similarity index 100% rename from test/fixtures/projects.yml rename to spec/fixtures/projects.yml diff --git a/test/fixtures/replies.yml b/spec/fixtures/replies.yml similarity index 100% rename from test/fixtures/replies.yml rename to spec/fixtures/replies.yml diff --git a/test/fixtures/reply.rb b/spec/fixtures/reply.rb similarity index 100% rename from test/fixtures/reply.rb rename to spec/fixtures/reply.rb diff --git a/test/fixtures/schema.rb b/spec/fixtures/schema.rb similarity index 100% rename from test/fixtures/schema.rb rename to spec/fixtures/schema.rb diff --git a/test/fixtures/topic.rb b/spec/fixtures/topic.rb similarity index 100% rename from test/fixtures/topic.rb rename to spec/fixtures/topic.rb diff --git a/test/fixtures/topics.yml b/spec/fixtures/topics.yml similarity index 100% rename from test/fixtures/topics.yml rename to spec/fixtures/topics.yml diff --git a/test/fixtures/user.rb b/spec/fixtures/user.rb similarity index 100% rename from test/fixtures/user.rb rename to spec/fixtures/user.rb diff --git a/test/fixtures/users.yml b/spec/fixtures/users.yml similarity index 100% rename from test/fixtures/users.yml rename to spec/fixtures/users.yml diff --git a/test/finder_test.rb b/test/finder_test.rb index 4fe7ef178..136306dc2 100644 --- a/test/finder_test.rb +++ b/test/finder_test.rb @@ -8,10 +8,6 @@ class FinderTest < ActiveRecordTestCase fixtures :topics, :replies, :users, :projects, :developers_projects - def test_new_methods_presence - assert_respond_to_all Topic, %w(per_page paginate paginate_by_sql) - end - def test_simple_paginate assert_queries(1) do entries = Topic.paginate :page => nil @@ -26,30 +22,6 @@ def test_simple_paginate assert entries.empty? end end - - def test_parameter_api - # explicit :all should not break anything - assert_equal Topic.paginate(:page => nil), Topic.paginate(:all, :page => 1) - - # :count could be nil and we should still not cry - assert_nothing_raised { Topic.paginate :page => 1, :count => nil } - end - - def test_paginate_with_per_page - entries = Topic.paginate :page => 1, :per_page => 1 - assert_equal 1, entries.size - assert_equal 4, entries.total_pages - - # Developer class has explicit per_page at 10 - entries = Developer.paginate :page => 1 - assert_equal 10, entries.size - assert_equal 2, entries.total_pages - - entries = Developer.paginate :page => 1, :per_page => 5 - assert_equal 11, entries.total_entries - assert_equal 5, entries.size - assert_equal 3, entries.total_pages - end def test_paginate_with_order entries = Topic.paginate :page => 1, :order => 'created_at desc' @@ -286,105 +258,4 @@ def test_paginate_array_of_ids end end end - - uses_mocha 'internals' do - def test_implicit_all_with_dynamic_finders - Topic.expects(:find_all_by_foo).returns([]) - Topic.expects(:count).returns(0) - Topic.paginate_by_foo :page => 2 - end - - def test_guessing_the_total_count - Topic.expects(:find).returns(Array.new(2)) - Topic.expects(:count).never - - entries = Topic.paginate :page => 2, :per_page => 4 - assert_equal 6, entries.total_entries - end - - def test_guessing_that_there_are_no_records - Topic.expects(:find).returns([]) - Topic.expects(:count).never - - entries = Topic.paginate :page => 1, :per_page => 4 - assert_equal 0, entries.total_entries - end - - def test_extra_parameters_stay_untouched - Topic.expects(:find).with(:all, {:foo => 'bar', :limit => 4, :offset => 0 }).returns(Array.new(5)) - Topic.expects(:count).with({:foo => 'bar'}).returns(1) - - Topic.paginate :foo => 'bar', :page => 1, :per_page => 4 - end - - def test_count_skips_select - Developer.stubs(:find).returns([]) - Developer.expects(:count).with({}).returns(0) - Developer.paginate :select => 'salary', :page => 2 - end - - def test_count_select_when_distinct - Developer.stubs(:find).returns([]) - Developer.expects(:count).with(:select => 'DISTINCT salary').returns(0) - Developer.paginate :select => 'DISTINCT salary', :page => 2 - end - - def test_should_use_scoped_finders_if_present - # scope-out compatibility - Topic.expects(:find_best).returns(Array.new(5)) - Topic.expects(:with_best).returns(1) - - Topic.paginate_best :page => 1, :per_page => 4 - end - - def test_paginate_by_sql - assert_respond_to Developer, :paginate_by_sql - Developer.expects(:find_by_sql).with(regexp_matches(/sql LIMIT 3(,| OFFSET) 3/)).returns([]) - Developer.expects(:count_by_sql).with('SELECT COUNT(*) FROM (sql) AS count_table').returns(0) - - entries = Developer.paginate_by_sql 'sql', :page => 2, :per_page => 3 - end - - def test_paginate_by_sql_respects_total_entries_setting - Developer.expects(:find_by_sql).returns([]) - Developer.expects(:count_by_sql).never - - entries = Developer.paginate_by_sql 'sql', :page => 1, :total_entries => 999 - assert_equal 999, entries.total_entries - end - - def test_paginate_by_sql_strips_order_by_when_counting - Developer.expects(:find_by_sql).returns([]) - Developer.expects(:count_by_sql).with("SELECT COUNT(*) FROM (sql\n ) AS count_table").returns(0) - - Developer.paginate_by_sql "sql\n ORDER\nby foo, bar, `baz` ASC", :page => 2 - end - - # TODO: counts are still wrong - def test_ability_to_use_with_custom_finders - # acts_as_taggable defines find_tagged_with(tag, options) - Topic.expects(:find_tagged_with).with('will_paginate', :offset => 5, :limit => 5).returns([]) - Topic.expects(:count).with({}).returns(0) - - Topic.paginate_tagged_with 'will_paginate', :page => 2, :per_page => 5 - end - - def test_array_argument_doesnt_eliminate_count - ids = (1..8).to_a - Developer.expects(:find_all_by_id).returns([]) - Developer.expects(:count).returns(0) - - Developer.paginate_by_id(ids, :per_page => 3, :page => 2, :order => 'id') - end - - def test_paginating_finder_doesnt_mangle_options - Developer.expects(:find).returns([]) - options = { :page => 1 } - options.expects(:delete).never - options_before = options.dup - - Developer.paginate(options) - assert_equal options, options_before - end - end end From f8f176808f35e16c2656c13c53a186dca8c19b5a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mislav=20Marohni=C4=87?= Date: Fri, 30 May 2008 12:26:33 +0200 Subject: [PATCH 016/168] spec/console; activerecord fixtures; integration specs --- {test => spec}/console | 4 +- spec/console_fixtures.rb | 8 ++ spec/finders/active_record_spec.rb | 125 ++++++++++++++++++++++++++++- test/finder_test.rb | 65 --------------- test/lib/load_fixtures.rb | 10 --- 5 files changed, 132 insertions(+), 80 deletions(-) rename {test => spec}/console (54%) create mode 100644 spec/console_fixtures.rb delete mode 100644 test/lib/load_fixtures.rb diff --git a/test/console b/spec/console similarity index 54% rename from test/console rename to spec/console index 3f282f114..0d3a3602c 100755 --- a/test/console +++ b/spec/console @@ -3,6 +3,6 @@ irb = RUBY_PLATFORM =~ /(:?mswin|mingw)/ ? 'irb.bat' : 'irb' libs = [] libs << 'irb/completion' -libs << File.join('lib', 'load_fixtures') +libs << 'console_fixtures' -exec "#{irb} -Ilib:test#{libs.map{ |l| " -r #{l}" }.join} --simple-prompt" +exec "#{irb} -Ilib:spec#{libs.map{ |l| " -r #{l}" }.join} --simple-prompt" diff --git a/spec/console_fixtures.rb b/spec/console_fixtures.rb new file mode 100644 index 000000000..1f0853f60 --- /dev/null +++ b/spec/console_fixtures.rb @@ -0,0 +1,8 @@ +require 'will_paginate/finders/active_record' +require 'finders/activerecord_test_connector' +ActiverecordTestConnector.setup + +# load all fixtures +Fixtures.create_fixtures(ActiverecordTestConnector::FIXTURES_PATH, ActiveRecord::Base.connection.tables) + + diff --git a/spec/finders/active_record_spec.rb b/spec/finders/active_record_spec.rb index c9b01213f..e0f42382b 100644 --- a/spec/finders/active_record_spec.rb +++ b/spec/finders/active_record_spec.rb @@ -9,8 +9,36 @@ class ArProject < ActiveRecord::Base describe WillPaginate::Finders::ActiveRecord do - before :all do - # Fixtures.create_fixtures ActiverecordTestConnector::FIXTURES_PATH, %w() + def self.fixtures(*tables) + table_names = tables.map { |t| t.to_s } + + fixtures = Fixtures.create_fixtures ActiverecordTestConnector::FIXTURES_PATH, table_names + @@loaded_fixtures = {} + @@fixture_cache = {} + + unless fixtures.nil? + if fixtures.instance_of?(Fixtures) + @@loaded_fixtures[fixtures.table_name] = fixtures + else + fixtures.each { |f| @@loaded_fixtures[f.table_name] = f } + end + end + + table_names.each do |table_name| + define_method(table_name) do |*fixtures| + @@fixture_cache[table_name] ||= {} + + instances = fixtures.map do |fixture| + if @@loaded_fixtures[table_name][fixture.to_s] + @@fixture_cache[table_name][fixture] ||= @@loaded_fixtures[table_name][fixture.to_s].find + else + raise StandardError, "No fixture with name '#{fixture}' found for table '#{table_name}'" + end + end + + instances.size == 1 ? instances.first : instances + end + end end it "should integrate with ActiveRecord::Base" do @@ -132,7 +160,98 @@ class ArProject < ActiveRecord::Base end if ActiverecordTestConnector.able_to_connect - # fixture-dependent tests here + fixtures :topics, :replies, :users, :projects, :developers_projects + + it "should get first page of Topics with a single query" do + lambda { + result = Topic.paginate :page => nil + result.current_page.should == 1 + result.total_pages.should == 1 + result.size.should == 4 + }.should run_queries + end + + it "should get second (inexistent) page of Topics, requiring 2 queries" do + lambda { + result = Topic.paginate :page => 2 + result.total_pages.should == 1 + result.should be_empty + }.should run_queries(2) + end + + it "should paginate with :order" do + result = Topic.paginate :page => 1, :order => 'created_at DESC' + result.should == topics(:futurama, :harvey_birdman, :rails, :ar).reverse + result.total_pages.should == 1 + end + + it "should paginate with :conditions" do + result = Topic.paginate :page => 1, :conditions => ["created_at > ?", 30.minutes.ago] + result.should == topics(:rails, :ar) + result.total_pages.should == 1 + end + + it "should paginate with :include and :conditions" do + result = Topic.paginate \ + :page => 1, + :include => :replies, + :conditions => "replies.content LIKE 'Bird%' ", + :per_page => 10 + + expected = Topic.find :all, + :include => 'replies', + :conditions => "replies.content LIKE 'Bird%' ", + :limit => 10 + + result.should == expected + result.total_entries.should == 1 + end + + it "should paginate with :include and :order" do + result = nil + lambda { + result = Topic.paginate \ + :page => 1, + :include => :replies, + :order => 'replies.created_at asc, topics.created_at asc', + :per_page => 10 + }.should run_queries(2) + + expected = Topic.find :all, + :include => 'replies', + :order => 'replies.created_at asc, topics.created_at asc', + :limit => 10 + + result.should == expected + result.total_entries.should == 4 + end end + + protected + + def run_queries(num = 1) + QueryCountMatcher.new(num) + end end + +class QueryCountMatcher + def initialize(num) + @queries = num + @old_query_count = $query_count + end + + def matches?(block) + block.call + @queries_run = $query_count - @old_query_count + @queries == @queries_run + end + + def failure_message + "expected #{@queries} queries, got #{@queries_run}" + end + + def negative_failure_message + "expected query count not to be #{$queries}" + end +end \ No newline at end of file diff --git a/test/finder_test.rb b/test/finder_test.rb index 136306dc2..100ee01c5 100644 --- a/test/finder_test.rb +++ b/test/finder_test.rb @@ -6,72 +6,7 @@ WillPaginate.enable_named_scope class FinderTest < ActiveRecordTestCase - fixtures :topics, :replies, :users, :projects, :developers_projects - - def test_simple_paginate - assert_queries(1) do - entries = Topic.paginate :page => nil - assert_equal 1, entries.current_page - assert_equal 1, entries.total_pages - assert_equal 4, entries.size - end - - assert_queries(2) do - entries = Topic.paginate :page => 2 - assert_equal 1, entries.total_pages - assert entries.empty? - end - end - - def test_paginate_with_order - entries = Topic.paginate :page => 1, :order => 'created_at desc' - expected = [topics(:futurama), topics(:harvey_birdman), topics(:rails), topics(:ar)].reverse - assert_equal expected, entries.to_a - assert_equal 1, entries.total_pages - end - - def test_paginate_with_conditions - entries = Topic.paginate :page => 1, :conditions => ["created_at > ?", 30.minutes.ago] - expected = [topics(:rails), topics(:ar)] - assert_equal expected, entries.to_a - assert_equal 1, entries.total_pages - end - - def test_paginate_with_include_and_conditions - entries = Topic.paginate \ - :page => 1, - :include => :replies, - :conditions => "replies.content LIKE 'Bird%' ", - :per_page => 10 - - expected = Topic.find :all, - :include => 'replies', - :conditions => "replies.content LIKE 'Bird%' ", - :limit => 10 - - assert_equal expected, entries.to_a - assert_equal 1, entries.total_entries - end - def test_paginate_with_include_and_order - entries = nil - assert_queries(2) do - entries = Topic.paginate \ - :page => 1, - :include => :replies, - :order => 'replies.created_at asc, topics.created_at asc', - :per_page => 10 - end - - expected = Topic.find :all, - :include => 'replies', - :order => 'replies.created_at asc, topics.created_at asc', - :limit => 10 - - assert_equal expected, entries.to_a - assert_equal 4, entries.total_entries - end - def test_paginate_associations_with_include entries, project = nil, projects(:active_record) diff --git a/test/lib/load_fixtures.rb b/test/lib/load_fixtures.rb deleted file mode 100644 index bb164f0bf..000000000 --- a/test/lib/load_fixtures.rb +++ /dev/null @@ -1,10 +0,0 @@ -require 'boot' -require 'lib/activerecord_test_connector' - -# setup the connection -ActiveRecordTestConnector.setup - -# load all fixtures -Fixtures.create_fixtures(ActiveRecordTestConnector::FIXTURES_PATH, ActiveRecord::Base.connection.tables) - -require 'will_paginate/finders/active_record' From 177b217bdc3caa0cfe2d4e41be15e1a45417ea4b Mon Sep 17 00:00:00 2001 From: Brandon Arbini Date: Thu, 29 May 2008 16:12:11 -0700 Subject: [PATCH 017/168] Refactored wp_count to pass options to wp_parse_count_options --- lib/will_paginate/finders/active_record.rb | 33 +++++++++++++--------- 1 file changed, 20 insertions(+), 13 deletions(-) diff --git a/lib/will_paginate/finders/active_record.rb b/lib/will_paginate/finders/active_record.rb index 5e065a37a..a13a35eef 100644 --- a/lib/will_paginate/finders/active_record.rb +++ b/lib/will_paginate/finders/active_record.rb @@ -122,23 +122,13 @@ def wp_query(options, pager, args, &block) # Does the not-so-trivial job of finding out the total number of entries # in the database. It relies on the ActiveRecord +count+ method. def wp_count(options, args, finder) - excludees = [:count, :order, :limit, :offset, :readonly] - unless options[:select] and options[:select] =~ /^\s*DISTINCT\b/i - excludees << :select # only exclude the select param if it doesn't begin with DISTINCT - end - # count expects (almost) the same options as find - count_options = options.except *excludees - - # merge the hash found in :count - # this allows you to specify :select, :order, or anything else just for the count query - count_options.update options[:count] if options[:count] + # find out if we are in a model or an association proxy + klass = (@owner and @reflection) ? @reflection.klass : self + count_options = wp_parse_count_options(options, klass) # we may have to scope ... counter = Proc.new { count(count_options) } - # we may be in a model or an association proxy! - klass = (@owner and @reflection) ? @reflection.klass : self - count = if finder.index('find_') == 0 and klass.respond_to?(scoper = finder.sub('find', 'with')) # scope_out adds a 'with_finder' method which acts like with_scope, if it's present # then execute the count with the scoping provided by the with_finder @@ -154,6 +144,23 @@ def wp_count(options, args, finder) count.respond_to?(:length) ? count.length : count end + + def wp_parse_count_options(options, klass) + excludees = [:count, :order, :limit, :offset, :readonly] + + unless options[:select] and options[:select] =~ /^\s*DISTINCT\b/i + # only exclude the select param if it doesn't begin with DISTINCT + excludees << :select + end + # count expects (almost) the same options as find + count_options = options.except *excludees + + # merge the hash found in :count + # this allows you to specify :select, :order, or anything else just for the count query + count_options.update options[:count] if options[:count] + + count_options + end end end From 1f990837bcabf1c89e93e3b0d5d9e2b0bb67a79b Mon Sep 17 00:00:00 2001 From: Denis Barushev Date: Thu, 15 May 2008 21:11:22 +0300 Subject: [PATCH 018/168] Remove :include option from count_all query when it's possible. --- lib/will_paginate/finders/active_record.rb | 9 ++++++++- spec/finders/active_record_spec.rb | 18 ++++++++++++++++++ 2 files changed, 26 insertions(+), 1 deletion(-) diff --git a/lib/will_paginate/finders/active_record.rb b/lib/will_paginate/finders/active_record.rb index a13a35eef..7fdc837ef 100644 --- a/lib/will_paginate/finders/active_record.rb +++ b/lib/will_paginate/finders/active_record.rb @@ -158,7 +158,14 @@ def wp_parse_count_options(options, klass) # merge the hash found in :count # this allows you to specify :select, :order, or anything else just for the count query count_options.update options[:count] if options[:count] - + + # forget about includes if they are irrelevant (Rails 2.1) + if count_options[:include] and + klass.private_methods.include?('references_eager_loaded_tables?') and + !klass.send(:references_eager_loaded_tables?, count_options) + count_options.delete :include + end + count_options end end diff --git a/spec/finders/active_record_spec.rb b/spec/finders/active_record_spec.rb index e0f42382b..772686cb8 100644 --- a/spec/finders/active_record_spec.rb +++ b/spec/finders/active_record_spec.rb @@ -225,6 +225,24 @@ def self.fixtures(*tables) result.should == expected result.total_entries.should == 4 end + + # detect ActiveRecord 2.1 + if ActiveRecord::Base.private_methods.include?('references_eager_loaded_tables?') + it "should remove :include for count" do + Developer.expects(:find).returns([1]) + Developer.expects(:count).with({}).returns(0) + + Developer.paginate :page => 1, :per_page => 1, :include => :projects + end + + it "should keep :include for count when they are referenced in :conditions" do + Developer.expects(:find).returns([1]) + Developer.expects(:count).with({ :include => :projects, :conditions => 'projects.id > 2' }).returns(0) + + Developer.paginate :page => 1, :per_page => 1, + :include => :projects, :conditions => 'projects.id > 2' + end + end end protected From ae1d62221af01659d935f6c1a2af1ef72fc480be Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mislav=20Marohni=C4=87?= Date: Sat, 31 May 2008 02:20:14 +0200 Subject: [PATCH 019/168] ActiveRecord unit tests -> specs --- spec/finders/active_record_spec.rb | 73 ++++++++++++++++++++++++++++++ test/finder_test.rb | 69 ---------------------------- 2 files changed, 73 insertions(+), 69 deletions(-) diff --git a/spec/finders/active_record_spec.rb b/spec/finders/active_record_spec.rb index 772686cb8..36e183e4e 100644 --- a/spec/finders/active_record_spec.rb +++ b/spec/finders/active_record_spec.rb @@ -148,6 +148,19 @@ def self.fixtures(*tables) ArProject.paginate_by_id(ids, :per_page => 3, :page => 2, :order => 'id') end + + # Is this Rails 2.0? Find out by testing find_all which was removed in [6998] + unless ActiveRecord::Base.respond_to? :find_all + it "should paginate array of IDs" do + # AR finders also accept arrays of IDs + # (this was broken in Rails before [6912]) + lambda { + result = Developer.paginate((1..8).to_a, :per_page => 3, :page => 2, :order => 'id') + result.map(&:id).should == (4..6).to_a + result.total_entries.should == 8 + }.should run_queries(1) + end + end it "doesn't mangle options" do ArProject.expects(:find).returns([]) @@ -243,6 +256,66 @@ def self.fixtures(*tables) :include => :projects, :conditions => 'projects.id > 2' end end + + describe "associations" do + it "should paginate with include" do + project = projects(:active_record) + + result = project.topics.paginate \ + :page => 1, + :include => :replies, + :conditions => ["replies.content LIKE ?", 'Nice%'], + :per_page => 10 + + expected = Topic.find :all, + :include => 'replies', + :conditions => ["project_id = #{project.id} AND replies.content LIKE ?", 'Nice%'], + :limit => 10 + + result.should == expected + end + + it "should paginate" do + dhh = users(:david) + expected_name_ordered = projects(:action_controller, :active_record) + expected_id_ordered = projects(:active_record, :action_controller) + + lambda { + # with association-specified order + result = dhh.projects.paginate(:page => 1) + result.should == expected_name_ordered + result.total_entries.should == 2 + }.should run_queries(2) + + # with explicit order + result = dhh.projects.paginate(:page => 1, :order => 'projects.id') + result.should == expected_id_ordered + result.total_entries.should == 2 + + lambda { + dhh.projects.find(:all, :order => 'projects.id', :limit => 4) + }.should_not raise_error + + result = dhh.projects.paginate(:page => 1, :order => 'projects.id', :per_page => 4) + result.should == expected_id_ordered + + # has_many with implicit order + topic = Topic.find(1) + expected = replies(:spam, :witty_retort) + # FIXME: wow, this is ugly + topic.replies.paginate(:page => 1).map(&:id).sort.should == expected.map(&:id).sort + topic.replies.paginate(:page => 1, :order => 'replies.id ASC').should == expected.reverse + end + + it "should paginate through association extension" do + project = Project.find(:first) + + lambda { + result = project.replies.paginate_recent :page => 1 + result.should == [replies(:brave)] + }.should run_queries(2) + end + end end protected diff --git a/test/finder_test.rb b/test/finder_test.rb index 100ee01c5..479a84aa4 100644 --- a/test/finder_test.rb +++ b/test/finder_test.rb @@ -7,63 +7,6 @@ class FinderTest < ActiveRecordTestCase - def test_paginate_associations_with_include - entries, project = nil, projects(:active_record) - - assert_nothing_raised "THIS IS A BUG in Rails 1.2.3 that was fixed in [7326]. " + - "Please upgrade to a newer version of Rails." do - entries = project.topics.paginate \ - :page => 1, - :include => :replies, - :conditions => "replies.content LIKE 'Nice%' ", - :per_page => 10 - end - - expected = Topic.find :all, - :include => 'replies', - :conditions => "project_id = #{project.id} AND replies.content LIKE 'Nice%' ", - :limit => 10 - - assert_equal expected, entries.to_a - end - - def test_paginate_associations - dhh = users :david - expected_name_ordered = [projects(:action_controller), projects(:active_record)] - expected_id_ordered = [projects(:active_record), projects(:action_controller)] - - assert_queries(2) do - # with association-specified order - entries = dhh.projects.paginate(:page => 1) - assert_equal expected_name_ordered, entries - assert_equal 2, entries.total_entries - end - - # with explicit order - entries = dhh.projects.paginate(:page => 1, :order => 'projects.id') - assert_equal expected_id_ordered, entries - assert_equal 2, entries.total_entries - - assert_nothing_raised { dhh.projects.find(:all, :order => 'projects.id', :limit => 4) } - entries = dhh.projects.paginate(:page => 1, :order => 'projects.id', :per_page => 4) - assert_equal expected_id_ordered, entries - - # has_many with implicit order - topic = Topic.find(1) - expected = [replies(:spam), replies(:witty_retort)] - assert_equal expected.map(&:id).sort, topic.replies.paginate(:page => 1).map(&:id).sort - assert_equal expected.reverse, topic.replies.paginate(:page => 1, :order => 'replies.id ASC') - end - - def test_paginate_association_extension - project = Project.find(:first) - - assert_queries(2) do - entries = project.replies.paginate_recent :page => 1 - assert_equal [replies(:brave)], entries - end - end - def test_paginate_with_joins entries = nil @@ -181,16 +124,4 @@ def xtest_pagination_defines_method assert User.methods.include?(pager), "`#{pager}` method should be defined on User" end - # Is this Rails 2.0? Find out by testing find_all which was removed in [6998] - unless ActiveRecord::Base.respond_to? :find_all - def test_paginate_array_of_ids - # AR finders also accept arrays of IDs - # (this was broken in Rails before [6912]) - assert_queries(1) do - entries = Developer.paginate((1..8).to_a, :per_page => 3, :page => 2, :order => 'id') - assert_equal (4..6).to_a, entries.map(&:id) - assert_equal 8, entries.total_entries - end - end - end end From c1856887318e69daf001f39c642dfda429ff20c9 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mislav=20Marohni=C4=87?= Date: Sat, 31 May 2008 05:14:59 +0200 Subject: [PATCH 020/168] WP::Finders::Common is now WP::Finders::Base (ditto ViewHelpers::Base) --- lib/will_paginate/finders/active_record.rb | 4 ++-- lib/will_paginate/finders/active_resource.rb | 4 ++-- lib/will_paginate/finders/{common.rb => base.rb} | 2 +- lib/will_paginate/finders/data_mapper.rb | 4 ++-- lib/will_paginate/view_helpers/action_view.rb | 4 ++-- spec/finders_spec.rb | 6 +++--- 6 files changed, 12 insertions(+), 12 deletions(-) rename lib/will_paginate/finders/{common.rb => base.rb} (99%) diff --git a/lib/will_paginate/finders/active_record.rb b/lib/will_paginate/finders/active_record.rb index 7fdc837ef..2aca60167 100644 --- a/lib/will_paginate/finders/active_record.rb +++ b/lib/will_paginate/finders/active_record.rb @@ -1,4 +1,4 @@ -require 'will_paginate/finders/common' +require 'will_paginate/finders/base' require 'active_record' module WillPaginate::Finders @@ -36,7 +36,7 @@ module WillPaginate::Finders # most sense in the current context. Make that obvious to the user, also. # For perfomance reasons you will also want to add an index to that column. module ActiveRecord - include WillPaginate::Finders::Common + include WillPaginate::Finders::Base # Wraps +find_by_sql+ by simply adding LIMIT and OFFSET to your SQL string # based on the params otherwise used by paginating finds: +page+ and diff --git a/lib/will_paginate/finders/active_resource.rb b/lib/will_paginate/finders/active_resource.rb index 4f1014b03..9ba0236bf 100644 --- a/lib/will_paginate/finders/active_resource.rb +++ b/lib/will_paginate/finders/active_resource.rb @@ -1,4 +1,4 @@ -require 'will_paginate/finders/common' +require 'will_paginate/finders/base' require 'active_resource' module WillPaginate::Finders @@ -6,7 +6,7 @@ module WillPaginate::Finders # # @posts = Post.paginate :all, :params => { :page => params[:page], :order => 'created_at DESC' } module ActiveResource - include WillPaginate::Finders::Common + include WillPaginate::Finders::Base protected diff --git a/lib/will_paginate/finders/common.rb b/lib/will_paginate/finders/base.rb similarity index 99% rename from lib/will_paginate/finders/common.rb rename to lib/will_paginate/finders/base.rb index d50146f89..99a885414 100644 --- a/lib/will_paginate/finders/common.rb +++ b/lib/will_paginate/finders/base.rb @@ -3,7 +3,7 @@ module WillPaginate module Finders # Database-agnostic finder logic - module Common + module Base # Default per-page limit def per_page() 30 end diff --git a/lib/will_paginate/finders/data_mapper.rb b/lib/will_paginate/finders/data_mapper.rb index 127394b15..4f5d3941b 100644 --- a/lib/will_paginate/finders/data_mapper.rb +++ b/lib/will_paginate/finders/data_mapper.rb @@ -1,9 +1,9 @@ -require 'will_paginate/finders/common' +require 'will_paginate/finders/base' require 'data_mapper' module WillPaginate::Finders module DataMapper - include WillPaginate::Finders::Common + include WillPaginate::Finders::Base protected diff --git a/lib/will_paginate/view_helpers/action_view.rb b/lib/will_paginate/view_helpers/action_view.rb index ceb97e08e..daf97ad51 100644 --- a/lib/will_paginate/view_helpers/action_view.rb +++ b/lib/will_paginate/view_helpers/action_view.rb @@ -1,5 +1,5 @@ require 'will_paginate/core_ext' -require 'will_paginate/view_helpers/common' +require 'will_paginate/view_helpers/base' require 'action_view' require 'will_paginate/view_helpers/link_renderer' @@ -7,7 +7,7 @@ module WillPaginate module ViewHelpers # ActionView helpers for Rails integration module ActionView - include WillPaginate::ViewHelpers::Common + include WillPaginate::ViewHelpers::Base def will_paginate(collection = nil, options = {}) options, collection = collection, nil if collection.is_a? Hash diff --git a/spec/finders_spec.rb b/spec/finders_spec.rb index 57ef69e2e..39a062e41 100644 --- a/spec/finders_spec.rb +++ b/spec/finders_spec.rb @@ -1,11 +1,11 @@ require 'spec_helper' -require 'will_paginate/finders/common' +require 'will_paginate/finders/base' class Model - extend WillPaginate::Finders::Common + extend WillPaginate::Finders::Base end -describe WillPaginate::Finders::Common do +describe WillPaginate::Finders::Base do it "should define default per_page of 30" do Model.per_page.should == 30 end From c5db3e43a530a4da64ac40118e06eb9a63634812 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mislav=20Marohni=C4=87?= Date: Sun, 8 Jun 2008 04:33:15 +0200 Subject: [PATCH 021/168] bump version number to 2.5.0 and update README --- README.rdoc | 124 ++++++++++++++++------------------- lib/will_paginate/version.rb | 4 +- will_paginate.gemspec | 11 ++-- 3 files changed, 63 insertions(+), 76 deletions(-) diff --git a/README.rdoc b/README.rdoc index 34d0dd42c..a402a7ba0 100644 --- a/README.rdoc +++ b/README.rdoc @@ -1,90 +1,82 @@ = WillPaginate -Pagination is just limiting the number of records displayed. Why should you let -it get in your way while developing, then? This plugin makes magic happen. Did -you ever want to be able to do just this on a model: +Pagination is just limiting the number of records displayed. Why should you let it get in your way +while developing? + +This is how you paginate on an ActiveRecord model: Post.paginate :page => 1, :order => 'created_at DESC' -... and then render the page links with a single view helper? Well, now you -can. +Most of the time it's as simple as replacing "find" with "paginate" and specifying the page you want. Some resources to get you started: -* Your mind reels with questions? Join our - {Google group}[http://groups.google.com/group/will_paginate]. -* The will_paginate project page: http://github.com/mislav/will_paginate -* How to report bugs: http://github.com/mislav/will_paginate/wikis/report-bugs -* Ryan Bates made an awesome screencast[http://railscasts.com/episodes/51], - check it out. +* The {will_paginate project page}[http://github.com/mislav/will_paginate]; +* Your mind reels with questions? Join our {Google group}[http://groups.google.com/group/will_paginate]; +* {How to report bugs}[http://github.com/mislav/will_paginate/wikis/report-bugs]; +* {Watch the will_paginate screencast}[http://railscasts.com/episodes/51] by Ryan Bates. + == Installation The recommended way is that you get the gem: - # add GitHub to your local list of gem sources: - gem sources -a http://gems.github.com/ - - # install the gem: - gem install mislav-will_paginate + gem install --source=http://gems.github.com/ mislav-will_paginate + +After that you don't need the will_paginate plugin in your Rails application anymore. In +Rails 2.1, add a gem dependency: -After that you don't need the will_paginate plugin in your Rails -application anymore. Just add a simple require to the end of -"config/environment.rb": + config.gem 'mislav-will_paginate', :lib => 'will_paginate', :version => '~> 2.5' - gem 'mislav-will_paginate', '~> 2.2' +If you're using Rails 2.0 or older, just add a simple require to the end of your +"config/environment.rb" instead: + + gem 'mislav-will_paginate', '~> 2.5' require 'will_paginate' -That's it. Remember to install the gem on all machines that you are -deploying to. +That's it. Remember to install the gem on all machines that you are deploying to. -There are extensive -{installation instructions}[http://github.com/mislav/will_paginate/wikis/installation] -on {the wiki}[http://github.com/mislav/will_paginate/wikis]. +There are extensive {installation +instructions}[http://github.com/mislav/will_paginate/wikis/installation] on {the +wiki}[http://github.com/mislav/will_paginate/wikis]. == Example usage Use a paginate finder in the controller: - @posts = Post.paginate_by_board_id @board.id, :page => params[:page], :order => 'updated_at DESC' + @posts = Post.paginate_by_board_id( + @board.id, + :page => params[:page], + :order => 'updated_at DESC' + ) -Yeah, +paginate+ works just like +find+ -- it just doesn't fetch all the -records. Don't forget to tell it which page you want, or it will complain! -Read more on WillPaginate::Finder::ClassMethods. +Yeah, +paginate+ works just like +find+ -- it just doesn't fetch all the records. Don't forget to +tell it which page you want, or it will complain! Read more about WillPaginate::Finders. -Render the posts in your view like you would normally do. When you need to render -pagination, just stick this in: +Render the posts in your view like you would normally do. When you need to render pagination, just +stick this in: <%= will_paginate @posts %> -You're done. (Copy and paste the example fancy CSS styles from the bottom.) You -can find the option list at WillPaginate::ViewHelpers. +You're done. (Copy and paste the example fancy CSS styles from the bottom.) You can find the option +list at WillPaginate::ViewHelpers. -How does it know how much items to fetch per page? It asks your model by calling -its per_page class method. You can define it like this: +How does it know how much items to fetch per page? It asks your model by calling its +per_page class method. You can define it like this: class Post < ActiveRecord::Base - cattr_reader :per_page - @@per_page = 50 + def self.per_page() 50 end end -... or like this: - - class Post < ActiveRecord::Base - def self.per_page - 50 - end - end - -... or don't worry about it at all. WillPaginate defines it to be 30 by default. -But you can always specify the count explicitly when calling +paginate+: +... or don't worry about it at all. WillPaginate defines it to be 30 by default. You can +always specify the count explicitly when calling +paginate+: @posts = Post.paginate :page => params[:page], :per_page => 50 -The +paginate+ finder wraps the original finder and returns your resultset that now has -some new properties. You can use the collection as you would with any ActiveRecord -resultset. WillPaginate view helpers also need that object to be able to render pagination: +The +paginate+ finder wraps the original finder and returns your result set that now has some new +properties. You can use the collection as you would use any other array. WillPaginate view helpers +also need that object to be able to render pagination:
    <% for post in @posts -%> @@ -97,7 +89,7 @@ resultset. WillPaginate view helpers also need that object to be able to render More detailed documentation: -* WillPaginate::Finder::ClassMethods for pagination on your models; +* WillPaginate::Finders for pagination on your models; * WillPaginate::ViewHelpers for your views. @@ -107,29 +99,25 @@ Authors:: Mislav Marohnić, PJ Hyett Original announcement:: http://errtheblog.com/post/929 Original PHP source:: http://www.strangerstudios.com/sandbox/pagination/diggstyle.php -All these people helped making will_paginate what it is now with their code -contributions or just simply awesome ideas: +All these people helped making will_paginate what it is now with their code contributions or just +simply awesome ideas: -Chris Wanstrath, Dr. Nic Williams, K. Adam Christensen, Mike Garey, Bence -Golda, Matt Aimonetti, Charles Brian Quinn, Desi McAdam, James Coglan, Matijs -van Zuijlen, Maria, Brendan Ribera, Todd Willey, Bryan Helmkamp, Jan Berkel, -Lourens Naudé, Rick Olson, Russell Norris, Piotr Usewicz, Chris Eppstein. +Chris Wanstrath, Dr. Nic Williams, K. Adam Christensen, Mike Garey, Bence Golda, Matt Aimonetti, +Charles Brian Quinn, Desi McAdam, James Coglan, Matijs van Zuijlen, Maria, Brendan Ribera, Todd +Willey, Bryan Helmkamp, Jan Berkel, Lourens Naudé, Rick Olson, Russell Norris, Piotr Usewicz, Chris +Eppstein. == Usable pagination in the UI -There are some CSS styles to get you started in the "examples/" directory. They -are showcased in the "examples/index.html" file. +There are some CSS styles to get you started in the "examples/" directory. They are showcased in the +"examples/index.html" file. More reading about pagination as design pattern: -* Pagination 101: - http://kurafire.net/log/archive/2007/06/22/pagination-101 -* Pagination gallery: - http://www.smashingmagazine.com/2007/11/16/pagination-gallery-examples-and-good-practices/ -* Pagination on Yahoo Design Pattern Library: - http://developer.yahoo.com/ypatterns/parent.php?pattern=pagination - -Want to discuss, request features, ask questions? Join the -{Google group}[http://groups.google.com/group/will_paginate]. +* {Pagination 101}[http://kurafire.net/log/archive/2007/06/22/pagination-101]; +* {Pagination gallery}[http://www.smashingmagazine.com/2007/11/16/pagination-gallery-examples-and-good-practices/] featured on Smashing Magazine; +* {Pagination design pattern}[http://developer.yahoo.com/ypatterns/parent.php?pattern=pagination] on Yahoo Design Pattern Library. +Want to discuss, request features, ask questions? Join the {Google +group}[http://groups.google.com/group/will_paginate]. \ No newline at end of file diff --git a/lib/will_paginate/version.rb b/lib/will_paginate/version.rb index 15feca612..ba92b54eb 100644 --- a/lib/will_paginate/version.rb +++ b/lib/will_paginate/version.rb @@ -1,8 +1,8 @@ module WillPaginate #:nodoc: module VERSION #:nodoc: MAJOR = 2 - MINOR = 3 - TINY = 1 + MINOR = 5 + TINY = 0 STRING = [MAJOR, MINOR, TINY].join('.') end diff --git a/will_paginate.gemspec b/will_paginate.gemspec index 499ed17d0..aa4d9223a 100644 --- a/will_paginate.gemspec +++ b/will_paginate.gemspec @@ -1,10 +1,10 @@ Gem::Specification.new do |s| s.name = 'will_paginate' - s.version = '2.3.1' - s.date = '2008-05-04' + s.version = '2.5.0' + # s.date = '2008-05-04' - s.summary = "Most awesome pagination solution for Rails" - s.description = "The will_paginate library provides a simple, yet powerful and extensible API for ActiveRecord pagination and rendering of pagination links in ActionView templates." + s.summary = "Most awesome pagination solution for every web app" + s.description = "The will_paginate library provides a simple, yet powerful and extensible API for pagination and rendering of page links in templates." s.authors = ['Mislav Marohnić', 'PJ Hyett'] s.email = 'mislav.marohnic@gmail.com' @@ -14,8 +14,7 @@ Gem::Specification.new do |s| s.rdoc_options = ['--main', 'README.rdoc'] s.rdoc_options << '--inline-source' << '--charset=UTF-8' s.extra_rdoc_files = ['README.rdoc', 'LICENSE', 'CHANGELOG'] - # s.add_dependency 'actionpack', ['>= 1.13.6'] s.files = %w(CHANGELOG LICENSE README.rdoc Rakefile examples examples/apple-circle.gif examples/index.haml examples/index.html examples/pagination.css examples/pagination.sass init.rb lib lib/will_paginate lib/will_paginate.rb lib/will_paginate/array.rb lib/will_paginate/collection.rb lib/will_paginate/core_ext.rb lib/will_paginate/finder.rb lib/will_paginate/named_scope.rb lib/will_paginate/named_scope_patch.rb lib/will_paginate/version.rb lib/will_paginate/view_helpers.rb test test/boot.rb test/collection_test.rb test/console test/database.yml test/finder_test.rb test/fixtures test/fixtures/admin.rb test/fixtures/developer.rb test/fixtures/developers_projects.yml test/fixtures/project.rb test/fixtures/projects.yml test/fixtures/replies.yml test/fixtures/reply.rb test/fixtures/schema.rb test/fixtures/topic.rb test/fixtures/topics.yml test/fixtures/user.rb test/fixtures/users.yml test/helper.rb test/lib test/lib/activerecord_test_case.rb test/lib/activerecord_test_connector.rb test/lib/load_fixtures.rb test/lib/view_test_process.rb test/view_test.rb) s.test_files = %w(test/boot.rb test/collection_test.rb test/console test/database.yml test/finder_test.rb test/fixtures test/fixtures/admin.rb test/fixtures/developer.rb test/fixtures/developers_projects.yml test/fixtures/project.rb test/fixtures/projects.yml test/fixtures/replies.yml test/fixtures/reply.rb test/fixtures/schema.rb test/fixtures/topic.rb test/fixtures/topics.yml test/fixtures/user.rb test/fixtures/users.yml test/helper.rb test/lib test/lib/activerecord_test_case.rb test/lib/activerecord_test_connector.rb test/lib/load_fixtures.rb test/lib/view_test_process.rb test/view_test.rb) -end +end \ No newline at end of file From c21486bf2eaee5a149320beb8163d25af66b4d27 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mislav=20Marohni=C4=87?= Date: Sun, 8 Jun 2008 05:10:22 +0200 Subject: [PATCH 022/168] set up rake spec:rcov --- Rakefile | 5 +++-- spec/rcov.opts | 2 ++ spec/tasks.rake | 15 +++++---------- 3 files changed, 10 insertions(+), 12 deletions(-) create mode 100644 spec/rcov.opts diff --git a/Rakefile b/Rakefile index d98e9600e..45ac0d622 100644 --- a/Rakefile +++ b/Rakefile @@ -1,6 +1,6 @@ require 'rubygems' begin - hanna_dir = '/home/mislav/projects/hanna/lib' + hanna_dir = '/Users/mislav/Projects/Hanna/lib' $:.unshift hanna_dir if File.exists? hanna_dir require 'hanna/rdoctask' rescue LoadError @@ -18,6 +18,7 @@ Rake::RDocTask.new(:rdoc) do |rdoc| rdoc.rdoc_files.include('README.rdoc', 'LICENSE', 'CHANGELOG'). include('lib/**/*.rb'). exclude('lib/will_paginate/named_scope*'). + exclude('lib/will_paginate/deprecation.rb'). exclude('lib/will_paginate/version.rb') rdoc.main = "README.rdoc" # page to start on @@ -59,4 +60,4 @@ end task :examples do %x(haml examples/index.haml examples/index.html) %x(sass examples/pagination.sass examples/pagination.css) -end +end \ No newline at end of file diff --git a/spec/rcov.opts b/spec/rcov.opts new file mode 100644 index 000000000..6b17c3200 --- /dev/null +++ b/spec/rcov.opts @@ -0,0 +1,2 @@ +--exclude ^\/,^spec\/,core_ext.rb,deprecation.rb +--no-validator-links \ No newline at end of file diff --git a/spec/tasks.rake b/spec/tasks.rake index a60cd39b8..cb0436659 100644 --- a/spec/tasks.rake +++ b/spec/tasks.rake @@ -1,39 +1,34 @@ require 'spec/rake/spectask' spec_opts = 'spec/spec.opts' -spec_glob = FileList['spec/**/*_spec.rb'] -desc 'Run all specs in spec directory' +desc 'Run all specs' Spec::Rake::SpecTask.new(:spec) do |t| t.libs << 'lib' << 'spec' t.spec_opts = ['--options', spec_opts] - t.spec_files = spec_glob end namespace :spec do - desc 'Run all specs in spec directory with RCov' + desc 'Analyze spec coverage with RCov' Spec::Rake::SpecTask.new(:rcov) do |t| t.libs << 'lib' << 'spec' t.spec_opts = ['--options', spec_opts] - t.spec_files = spec_glob t.rcov = true - # t.rcov_opts = lambda do - # IO.readlines('spec/rcov.opts').map {|l| l.chomp.split " "}.flatten - # end + t.rcov_opts = lambda do + IO.readlines('spec/rcov.opts').map { |l| l.chomp.split(" ") }.flatten + end end desc 'Print Specdoc for all specs' Spec::Rake::SpecTask.new(:doc) do |t| t.libs << 'lib' << 'spec' t.spec_opts = ['--format', 'specdoc', '--dry-run'] - t.spec_files = spec_glob end desc 'Generate HTML report' Spec::Rake::SpecTask.new(:html) do |t| t.libs << 'lib' << 'spec' t.spec_opts = ['--format', 'html:doc/spec_results.html', '--diff'] - t.spec_files = spec_glob t.fail_on_error = false end end From d860f448ae64b731c5410ce15e82a6daa21905bf Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mislav=20Marohni=C4=87?= Date: Sun, 8 Jun 2008 06:31:33 +0200 Subject: [PATCH 023/168] some old tests -> new LinkRendererBase specs --- spec/view_helpers/link_renderer_base_spec.rb | 120 +++++++++++++++++-- test/view_test.rb | 33 ----- 2 files changed, 112 insertions(+), 41 deletions(-) diff --git a/spec/view_helpers/link_renderer_base_spec.rb b/spec/view_helpers/link_renderer_base_spec.rb index ce16f93ae..d0e84b201 100644 --- a/spec/view_helpers/link_renderer_base_spec.rb +++ b/spec/view_helpers/link_renderer_base_spec.rb @@ -1,20 +1,124 @@ require 'spec_helper' require 'will_paginate/view_helpers/link_renderer_base' +require 'will_paginate/collection' + +class LegacyCollection < WillPaginate::Collection + alias :page_count :total_pages + undef :total_pages +end describe WillPaginate::ViewHelpers::LinkRendererBase do - it "should have gap marked initialized" do - @renderer = create + + before do + @renderer = WillPaginate::ViewHelpers::LinkRendererBase.new + end + + it "should have '...' as default gap marker" do @renderer.gap_marker.should == '...' end - + + it "should raise error when unprepared" do + lambda { + @renderer.send :param_name + }.should raise_error + end + it "should prepare with collection and options" do - @renderer = create - @renderer.prepare(collection, { :param_name => 'mypage' }) + prepare({}, :param_name => 'mypage') @renderer.send(:current_page).should == 1 @renderer.send(:param_name).should == 'mypage' end - - def create - WillPaginate::ViewHelpers::LinkRendererBase.new + + it "should have total_pages accessor" do + prepare :total_pages => 42 + lambda { + @renderer.send(:total_pages).should == 42 + }.should_not have_deprecation + end + + it "should log deprecation warnings for legacy collections" do + @renderer.prepare(LegacyCollection.new(1, 1, 2), {}) + lambda { + @renderer.send(:total_pages).should == 2 + }.should have_deprecation + end + + it "should clear old cached values when prepared" do + prepare({ :total_pages => 1 }, :param_name => 'foo') + @renderer.send(:total_pages).should == 1 + @renderer.send(:param_name).should == 'foo' + # prepare with different object and options: + prepare({ :total_pages => 2 }, :param_name => 'bar') + @renderer.send(:total_pages).should == 2 + @renderer.send(:param_name).should == 'bar' + end + + describe "visible page numbers" do + it "should calculate windowed visible links" do + prepare({ :page => 6, :total_pages => 11 }, :inner_window => 1, :outer_window => 1) + showing_pages 1, 2, 5, 6, 7, 10, 11 + end + + it "should eliminate small gaps" do + prepare({ :page => 6, :total_pages => 11 }, :inner_window => 2, :outer_window => 1) + # pages 4 and 8 appear instead of the gap + showing_pages 1..11 + end + + it "should support having no windows at all" do + prepare({ :page => 4, :total_pages => 7 }, :inner_window => 0, :outer_window => 0) + showing_pages 1, 4, 7 + end + + it "should adjust upper limit if lower is out of bounds" do + prepare({ :page => 1, :total_pages => 10 }, :inner_window => 2, :outer_window => 1) + showing_pages 1, 2, 3, 4, 5, 9, 10 + end + + it "should adjust lower limit if upper is out of bounds" do + prepare({ :page => 10, :total_pages => 10 }, :inner_window => 2, :outer_window => 1) + showing_pages 1, 2, 6, 7, 8, 9, 10 + end + + def showing_pages(*pages) + pages = pages.first.to_a if Array === pages.first or Range === pages.first + @renderer.send(:visible_page_numbers).should == pages + end end + + protected + + def prepare(collection_options, options = {}) + @renderer.prepare(collection(collection_options), options) + end + + def have_deprecation + DeprecationMatcher.new + end + end + +class DeprecationMatcher + def initialize + @old_behavior = WillPaginate::Deprecation.behavior + @messages = [] + WillPaginate::Deprecation.behavior = lambda { |message, callstack| + @messages << message + } + end + + def matches?(block) + block.call + !@messages.empty? + ensure + WillPaginate::Deprecation.behavior = @old_behavior + end + + def failure_message + "expected block to raise a deprecation warning" + end + + def negative_failure_message + "expected block not to raise deprecation warnings, #{@messages.size} raised" + end +end \ No newline at end of file diff --git a/test/view_test.rb b/test/view_test.rb index f015436f7..3cfeef40c 100644 --- a/test/view_test.rb +++ b/test/view_test.rb @@ -111,26 +111,6 @@ def test_will_paginate_without_page_links end end - def test_will_paginate_windows - paginate({ :page => 6, :per_page => 1 }, :inner_window => 1) do |pagination| - assert_select 'a[href]', 8 do |elements| - validate_page_numbers [5,1,2,5,7,10,11,7], elements - assert_select elements.first, 'a', '« Previous' - assert_select elements.last, 'a', 'Next »' - end - assert_select 'span.current', '6' - assert_equal '« Previous 1 2 … 5 6 7 … 10 11 Next »', pagination.first.inner_text - end - end - - def test_will_paginate_eliminates_small_gaps - paginate({ :page => 6, :per_page => 1 }, :inner_window => 2) do - assert_select 'a[href]', 12 do |elements| - validate_page_numbers [5,1,2,3,4,5,7,8,9,10,11,7], elements - end - end - end - def test_container_id paginate do |div| assert_nil div.first['id'] @@ -245,19 +225,6 @@ def test_custom_routing_with_first_page_hidden ## internal hardcore stuff ## - class LegacyCollection < WillPaginate::Collection - alias :page_count :total_pages - undef :total_pages - end - - def test_deprecation_notices_with_page_count - collection = LegacyCollection.new(1, 1, 2) - - assert_deprecated collection.class.name do - paginate collection - end - end - uses_mocha 'view internals' do def test_collection_name_can_be_guessed collection = mock From 16452f58394c697d68c3d6fe96b59a07f430d11e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mislav=20Marohni=C4=87?= Date: Sun, 8 Jun 2008 23:04:49 +0200 Subject: [PATCH 024/168] add per_page=(limit) attribute writer --- lib/will_paginate/finders/base.rb | 10 +++++++--- spec/finders_spec.rb | 9 +++++++++ 2 files changed, 16 insertions(+), 3 deletions(-) diff --git a/lib/will_paginate/finders/base.rb b/lib/will_paginate/finders/base.rb index 99a885414..f64324406 100644 --- a/lib/will_paginate/finders/base.rb +++ b/lib/will_paginate/finders/base.rb @@ -4,8 +4,13 @@ module WillPaginate module Finders # Database-agnostic finder logic module Base - # Default per-page limit - def per_page() 30 end + def per_page + @per_page ||= 30 + end + + def per_page=(limit) + @per_page = limit.to_i + end # This is the main paginating finder. # @@ -57,7 +62,6 @@ def paginated_each(options = {}, &block) def wp_parse_options(options) #:nodoc: raise ArgumentError, 'parameter hash expected' unless Hash === options - # options = options.symbolize_keys raise ArgumentError, ':page parameter required' unless options.key? :page if options[:count] and options[:total_entries] diff --git a/spec/finders_spec.rb b/spec/finders_spec.rb index 39a062e41..0782fbe53 100644 --- a/spec/finders_spec.rb +++ b/spec/finders_spec.rb @@ -9,6 +9,15 @@ class Model it "should define default per_page of 30" do Model.per_page.should == 30 end + + it "should allow to set custom per_page" do + begin + Model.per_page = 25 + Model.per_page.should == 25 + ensure + Model.per_page = 30 + end + end it "should result with WillPaginate::Collection" do Model.expects(:wp_query) From 172ef85ada50ceec42bc8c7016194d00de0dfea6 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mislav=20Marohni=C4=87?= Date: Mon, 9 Jun 2008 01:28:07 +0200 Subject: [PATCH 025/168] convert all remaining ActiveRecord tests to specs --- spec/finders/active_record_spec.rb | 110 ++++++++++++++++++++++++- test/finder_test.rb | 127 ----------------------------- 2 files changed, 107 insertions(+), 130 deletions(-) delete mode 100644 test/finder_test.rb diff --git a/spec/finders/active_record_spec.rb b/spec/finders/active_record_spec.rb index 36e183e4e..2d7597839 100644 --- a/spec/finders/active_record_spec.rb +++ b/spec/finders/active_record_spec.rb @@ -181,7 +181,7 @@ def self.fixtures(*tables) result.current_page.should == 1 result.total_pages.should == 1 result.size.should == 4 - }.should run_queries + }.should run_queries(1) end it "should get second (inexistent) page of Topics, requiring 2 queries" do @@ -309,18 +309,122 @@ def self.fixtures(*tables) it "should paginate through association extension" do project = Project.find(:first) + expected = [replies(:brave)] lambda { result = project.replies.paginate_recent :page => 1 - result.should == [replies(:brave)] + result.should == expected + }.should run_queries(1) + end + end + + it "should paginate with joins" do + result = nil + join_sql = 'LEFT JOIN developers_projects ON users.id = developers_projects.developer_id' + + lambda { + result = Developer.paginate :page => 1, :joins => join_sql, :conditions => 'project_id = 1' + result.size.should == 2 + developer_names = result.map(&:name) + developer_names.should include('David') + developer_names.should include('Jamis') + }.should run_queries(1) + + lambda { + expected = result.to_a + result = Developer.paginate :page => 1, :joins => join_sql, + :conditions => 'project_id = 1', :count => { :select => "users.id" } + result.should == expected + result.total_entries.should == 2 + }.should run_queries(1) + end + + it "should paginate with group" do + result = nil + lambda { + result = Developer.paginate :page => 1, :per_page => 10, + :group => 'salary', :select => 'salary', :order => 'salary' + }.should run_queries(1) + + expected = users(:david, :jamis, :dev_10, :poor_jamis).map(&:salary).sort + result.map(&:salary).should == expected + end + + it "should paginate with dynamic finder" do + expected = replies(:witty_retort, :spam) + Reply.paginate_by_topic_id(1, :page => 1).should == expected + + result = Developer.paginate :conditions => { :salary => 100000 }, :page => 1, :per_page => 5 + result.total_entries.should == 8 + Developer.paginate_by_salary(100000, :page => 1, :per_page => 5).should == result + end + + it "should paginate with dynamic finder and conditions" do + result = Developer.paginate_by_salary(100000, :page => 1, :conditions => ['id > ?', 6]) + result.total_entries.should == 4 + result.map(&:id).should == (7..10).to_a + end + + it "should raise error when dynamic finder is not recognized" do + lambda { + Developer.paginate_by_inexistent_attribute 100000, :page => 1 + }.should raise_error(NoMethodError) + end + + it "should paginate with_scope" do + result = Developer.with_poor_ones { Developer.paginate :page => 1 } + result.size.should == 2 + result.total_entries.should == 2 + end + + describe "named_scope" do + it "should paginate" do + result = Developer.poor.paginate :page => 1, :per_page => 1 + result.size.should == 1 + result.total_entries.should == 2 + end + + it "should paginate on habtm association" do + project = projects(:active_record) + lambda { + result = project.developers.poor.paginate :page => 1, :per_page => 1 + result.size.should == 1 + result.total_entries.should == 1 + }.should run_queries(2) + end + + it "should paginate on hmt association" do + project = projects(:active_record) + expected = [replies(:brave)] + + lambda { + result = project.replies.recent.paginate :page => 1, :per_page => 1 + result.should == expected + result.total_entries.should == 1 + }.should run_queries(2) + end + + it "should paginate on has_many association" do + project = projects(:active_record) + expected = [topics(:ar)] + + lambda { + result = project.topics.mentions_activerecord.paginate :page => 1, :per_page => 1 + result.should == expected + result.total_entries.should == 1 }.should run_queries(2) end end + + it "should paginate with :readonly option" do + lambda { Developer.paginate :readonly => true, :page => 1 }.should_not raise_error + end + end protected - def run_queries(num = 1) + def run_queries(num) QueryCountMatcher.new(num) end diff --git a/test/finder_test.rb b/test/finder_test.rb deleted file mode 100644 index 479a84aa4..000000000 --- a/test/finder_test.rb +++ /dev/null @@ -1,127 +0,0 @@ -require 'helper' -require 'lib/activerecord_test_case' - -require 'will_paginate' -require 'will_paginate/finders/active_record' -WillPaginate.enable_named_scope - -class FinderTest < ActiveRecordTestCase - - def test_paginate_with_joins - entries = nil - - assert_queries(1) do - entries = Developer.paginate :page => 1, - :joins => 'LEFT JOIN developers_projects ON users.id = developers_projects.developer_id', - :conditions => 'project_id = 1' - assert_equal 2, entries.size - developer_names = entries.map &:name - assert developer_names.include?('David') - assert developer_names.include?('Jamis') - end - - assert_queries(1) do - expected = entries.to_a - entries = Developer.paginate :page => 1, - :joins => 'LEFT JOIN developers_projects ON users.id = developers_projects.developer_id', - :conditions => 'project_id = 1', :count => { :select => "users.id" } - assert_equal expected, entries.to_a - assert_equal 2, entries.total_entries - end - end - - def test_paginate_with_group - entries = nil - assert_queries(1) do - entries = Developer.paginate :page => 1, :per_page => 10, - :group => 'salary', :select => 'salary', :order => 'salary' - end - - expected = [ users(:david), users(:jamis), users(:dev_10), users(:poor_jamis) ].map(&:salary).sort - assert_equal expected, entries.map(&:salary) - end - - def test_paginate_with_dynamic_finder - expected = [replies(:witty_retort), replies(:spam)] - assert_equal expected, Reply.paginate_by_topic_id(1, :page => 1) - - entries = Developer.paginate :conditions => { :salary => 100000 }, :page => 1, :per_page => 5 - assert_equal 8, entries.total_entries - assert_equal entries, Developer.paginate_by_salary(100000, :page => 1, :per_page => 5) - - # dynamic finder + conditions - entries = Developer.paginate_by_salary(100000, :page => 1, - :conditions => ['id > ?', 6]) - assert_equal 4, entries.total_entries - assert_equal (7..10).to_a, entries.map(&:id) - - assert_raises NoMethodError do - Developer.paginate_by_inexistent_attribute 100000, :page => 1 - end - end - - def test_scoped_paginate - entries = Developer.with_poor_ones { Developer.paginate :page => 1 } - - assert_equal 2, entries.size - assert_equal 2, entries.total_entries - end - - ## named_scope ## - - def test_paginate_in_named_scope - entries = Developer.poor.paginate :page => 1, :per_page => 1 - - assert_equal 1, entries.size - assert_equal 2, entries.total_entries - end - - def test_paginate_in_named_scope_on_habtm_association - project = projects(:active_record) - assert_queries(2) do - entries = project.developers.poor.paginate :page => 1, :per_page => 1 - - assert_equal 1, entries.size, 'one developer should be found' - assert_equal 1, entries.total_entries, 'only one developer should be found' - end - end - - def test_paginate_in_named_scope_on_hmt_association - project = projects(:active_record) - expected = [replies(:brave)] - - assert_queries(2) do - entries = project.replies.recent.paginate :page => 1, :per_page => 1 - assert_equal expected, entries - assert_equal 1, entries.total_entries, 'only one reply should be found' - end - end - - def test_paginate_in_named_scope_on_has_many_association - project = projects(:active_record) - expected = [topics(:ar)] - - assert_queries(2) do - entries = project.topics.mentions_activerecord.paginate :page => 1, :per_page => 1 - assert_equal expected, entries - assert_equal 1, entries.total_entries, 'only one topic should be found' - end - end - - ## misc ## - - def test_readonly - assert_nothing_raised { Developer.paginate :readonly => true, :page => 1 } - end - - # this functionality is temporarily removed - def xtest_pagination_defines_method - pager = "paginate_by_created_at" - assert !User.methods.include?(pager), "User methods should not include `#{pager}` method" - # paginate! - assert 0, User.send(pager, nil, :page => 1).total_entries - # the paging finder should now be defined - assert User.methods.include?(pager), "`#{pager}` method should be defined on User" - end - -end From acef1b6096862e6b4318607afe07c93f7300d1ee Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mislav=20Marohni=C4=87?= Date: Mon, 9 Jun 2008 01:29:05 +0200 Subject: [PATCH 026/168] autotest love: mappings, growl notifications, hacks --- .autotest | 81 +++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 81 insertions(+) create mode 100644 .autotest diff --git a/.autotest b/.autotest new file mode 100644 index 000000000..03fc9f42b --- /dev/null +++ b/.autotest @@ -0,0 +1,81 @@ +Autotest.add_hook :initialize do |at| + at.libs = 'lib:spec' + + at.clear_mappings + + at.add_mapping(%r{^lib/will_paginate/(.+)\.rb$}) { |_, match| + "spec/#{match[1]}_spec.rb" + } + at.add_mapping(%r{^spec/.+_spec\.rb$}) { |f, _| f } + at.add_mapping(%r{^spec/(finders/activerecord_test_connector.rb|database.yml|fixtures/.+)$}) { + 'spec/finders/active_record_spec.rb' + } + at.add_mapping(%r{^spec/((spec_helper|shared/.+)\.rb|spec.opts)$}) { + # simply re-run all specs + at.files_matching %r{^spec/.+_spec\.rb$} + } + + # add these to ignore list + %w{ .git test/ rails/ Rakefile README.rdoc init.rb .autotest + doc/ coverage/ LICENSE CHANGELOG .manifest will_paginate.gemspec examples/ + spec/tasks.rake spec/console spec/rcov.opts + }.each { |path| at.add_exception path } + +end + +module Autotest::Growl + def self.growl title, msg, pri = 0, img = nil + # title += " in #{Dir.pwd.split(/\//)[-3..-1].join("/")}" + # msg += " at #{Time.now.strftime('%Y-%m-%d %H:%M:%S')}" + + # TODO: parameterize default image + img ||= "/Applications/Mail.app/Contents/Resources/Caution.tiff" + cmd = "growlnotify -n autotest --image #{img} -p #{pri} -m #{msg.inspect} #{title.inspect}" + system cmd + end + + # Autotest.add_hook :initialize do |at| + # growl "autotest running", "Started" + # end + + Autotest.add_hook :red do |at| + growl "Tests Failed", "#{at.files_to_test.size} tests failed", 2 + end + + Autotest.add_hook :green do |at| + growl "Tests Passed", "Tests passed", -2 if at.tainted + end + + Autotest.add_hook :all_good do |at| + growl "Tests Passed", "All tests passed", -2 if at.tainted + end +end + +Autotest::Rspec.class_eval do + # RSpec guys forgot about `libs` in make_test_cmd + def make_test_cmd_with_libs(files_to_test) + make_test_cmd_without_libs(files_to_test).sub(' -S ', " -S -I#{libs} ") + end + + alias :make_test_cmd_without_libs :make_test_cmd + alias :make_test_cmd :make_test_cmd_with_libs + + # ugh, we have to monkeypatch Autotest ... + # the regexp it generates for the exception list just matches too much + # + # SOLUTION: wrap it up in another regexp that anchors the whole expression to + # the beginning of the path + def exceptions + unless defined? @exceptions then + if @exception_list.empty? then + @exceptions = nil + else + # old (BAD): + # @exceptions = Regexp.union(*@exception_list) + @exceptions = /^\.\/#{Regexp.union(*@exception_list)}/ + end + end + + @exceptions + end +end From a86f35528c6752dc0544fd833f7d28c58890d939 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mislav=20Marohni=C4=87?= Date: Mon, 9 Jun 2008 01:44:49 +0200 Subject: [PATCH 027/168] update CHANGELOG so people get the idea what's been going on in this branch --- CHANGELOG | 15 +++++++++++++++ 1 file changed, 15 insertions(+) diff --git a/CHANGELOG b/CHANGELOG index 660046328..7a174d70b 100644 --- a/CHANGELOG +++ b/CHANGELOG @@ -1,3 +1,18 @@ +== "agnostic" branch + +* setup Autotest +* added per_page=(limit) attribute writer to set default per_page +* Remove :include option from count_all query when possible (Rails 2.1) +* added WP::ViewHelpers::ActionView and LinkRenderer +* specs for ViewHelpers::Base and LinkRendererBase +* created LinkRendererBase that implements windowed visible page numbers logic +* created WP::ViewHelpers::Base abstract module that implements generic view helpers +* converted finder tests to specs +* added WP::Finders::DataMapper +* added WP::Finders::ActiveRecord mixin for ActiveRecord::Base +* created WP::Finders::Base abstract module that implements generic pagination logic +* removed dependency to ActiveSupport + == 2.3.1, released 2008-05-04 * Fixed page numbers not showing with custom routes and implicit first page From 5c1d95fb5b043c6116b468468120c1087890b778 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mislav=20Marohni=C4=87?= Date: Mon, 9 Jun 2008 01:50:54 +0200 Subject: [PATCH 028/168] remove last traces of ActiveRecord in old unit tests --- test/boot.rb | 3 +-- test/helper.rb | 2 +- test/lib/activerecord_test_case.rb | 36 ------------------------------ 3 files changed, 2 insertions(+), 39 deletions(-) delete mode 100644 test/lib/activerecord_test_case.rb diff --git a/test/boot.rb b/test/boot.rb index 622fc93c4..654621a03 100644 --- a/test/boot.rb +++ b/test/boot.rb @@ -6,7 +6,7 @@ if !version and framework_root = ["#{plugin_root}/rails", "#{plugin_root}/../../rails"].find { |p| File.directory? p } puts "found framework root: #{framework_root}" # this allows for a plugin to be tested outside of an app and without Rails gems - $:.unshift "#{framework_root}/activesupport/lib", "#{framework_root}/activerecord/lib", "#{framework_root}/actionpack/lib" + $:.unshift "#{framework_root}/activesupport/lib", "#{framework_root}/actionpack/lib" else # simply use installed gems if available puts "using Rails#{version ? ' ' + version : nil} gems" @@ -16,6 +16,5 @@ gem 'rails', version else gem 'actionpack' - gem 'activerecord' end end diff --git a/test/helper.rb b/test/helper.rb index ad52b1b65..8b054872a 100644 --- a/test/helper.rb +++ b/test/helper.rb @@ -4,7 +4,7 @@ # gem install redgreen for colored test output begin require 'redgreen'; rescue LoadError; end -require 'boot' unless defined?(ActiveRecord) +require 'boot' unless defined?(ActionView) class Test::Unit::TestCase protected diff --git a/test/lib/activerecord_test_case.rb b/test/lib/activerecord_test_case.rb deleted file mode 100644 index 8f66ebee4..000000000 --- a/test/lib/activerecord_test_case.rb +++ /dev/null @@ -1,36 +0,0 @@ -require 'lib/activerecord_test_connector' - -class ActiveRecordTestCase < Test::Unit::TestCase - # Set our fixture path - if ActiveRecordTestConnector.able_to_connect - self.fixture_path = File.join(File.dirname(__FILE__), '..', 'fixtures') - self.use_transactional_fixtures = true - end - - def self.fixtures(*args) - super if ActiveRecordTestConnector.connected - end - - def run(*args) - super if ActiveRecordTestConnector.connected - end - - # Default so Test::Unit::TestCase doesn't complain - def test_truth - end - - protected - - def assert_queries(num = 1) - $query_count = 0 - yield - ensure - assert_equal num, $query_count, "#{$query_count} instead of #{num} queries were executed." - end - - def assert_no_queries(&block) - assert_queries(0, &block) - end -end - -ActiveRecordTestConnector.setup From 79d380b931dff5affa020d5f0533d90d15ac4e61 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mislav=20Marohni=C4=87?= Date: Mon, 9 Jun 2008 01:57:43 +0200 Subject: [PATCH 029/168] specs: extract fixtures support code to activerecord_test_connector --- spec/finders/active_record_spec.rb | 32 +------------------ spec/finders/activerecord_test_connector.rb | 34 +++++++++++++++++++++ 2 files changed, 35 insertions(+), 31 deletions(-) diff --git a/spec/finders/active_record_spec.rb b/spec/finders/active_record_spec.rb index 2d7597839..e5e8337ae 100644 --- a/spec/finders/active_record_spec.rb +++ b/spec/finders/active_record_spec.rb @@ -9,37 +9,7 @@ class ArProject < ActiveRecord::Base describe WillPaginate::Finders::ActiveRecord do - def self.fixtures(*tables) - table_names = tables.map { |t| t.to_s } - - fixtures = Fixtures.create_fixtures ActiverecordTestConnector::FIXTURES_PATH, table_names - @@loaded_fixtures = {} - @@fixture_cache = {} - - unless fixtures.nil? - if fixtures.instance_of?(Fixtures) - @@loaded_fixtures[fixtures.table_name] = fixtures - else - fixtures.each { |f| @@loaded_fixtures[f.table_name] = f } - end - end - - table_names.each do |table_name| - define_method(table_name) do |*fixtures| - @@fixture_cache[table_name] ||= {} - - instances = fixtures.map do |fixture| - if @@loaded_fixtures[table_name][fixture.to_s] - @@fixture_cache[table_name][fixture] ||= @@loaded_fixtures[table_name][fixture.to_s].find - else - raise StandardError, "No fixture with name '#{fixture}' found for table '#{table_name}'" - end - end - - instances.size == 1 ? instances.first : instances - end - end - end + extend ActiverecordTestConnector::FixtureSetup it "should integrate with ActiveRecord::Base" do ActiveRecord::Base.should respond_to(:paginate) diff --git a/spec/finders/activerecord_test_connector.rb b/spec/finders/activerecord_test_connector.rb index 615891e7a..8d46afbc9 100644 --- a/spec/finders/activerecord_test_connector.rb +++ b/spec/finders/activerecord_test_connector.rb @@ -66,4 +66,38 @@ def execute_with_counting(sql, name = nil, &block) alias_method_chain :execute, :counting end end + + module FixtureSetup + def fixtures(*tables) + table_names = tables.map { |t| t.to_s } + + fixtures = Fixtures.create_fixtures ActiverecordTestConnector::FIXTURES_PATH, table_names + @@loaded_fixtures = {} + @@fixture_cache = {} + + unless fixtures.nil? + if fixtures.instance_of?(Fixtures) + @@loaded_fixtures[fixtures.table_name] = fixtures + else + fixtures.each { |f| @@loaded_fixtures[f.table_name] = f } + end + end + + table_names.each do |table_name| + define_method(table_name) do |*fixtures| + @@fixture_cache[table_name] ||= {} + + instances = fixtures.map do |fixture| + if @@loaded_fixtures[table_name][fixture.to_s] + @@fixture_cache[table_name][fixture] ||= @@loaded_fixtures[table_name][fixture.to_s].find + else + raise StandardError, "No fixture with name '#{fixture}' found for table '#{table_name}'" + end + end + + instances.size == 1 ? instances.first : instances + end + end + end + end end From 44eb0e91b221cf8364b8f3a06e42b73da81aff9f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mislav=20Marohni=C4=87?= Date: Tue, 17 Jun 2008 11:39:08 +0200 Subject: [PATCH 030/168] remove Growl integration --- .autotest | 28 ---------------------------- 1 file changed, 28 deletions(-) diff --git a/.autotest b/.autotest index 03fc9f42b..74090987c 100644 --- a/.autotest +++ b/.autotest @@ -23,34 +23,6 @@ Autotest.add_hook :initialize do |at| end -module Autotest::Growl - def self.growl title, msg, pri = 0, img = nil - # title += " in #{Dir.pwd.split(/\//)[-3..-1].join("/")}" - # msg += " at #{Time.now.strftime('%Y-%m-%d %H:%M:%S')}" - - # TODO: parameterize default image - img ||= "/Applications/Mail.app/Contents/Resources/Caution.tiff" - cmd = "growlnotify -n autotest --image #{img} -p #{pri} -m #{msg.inspect} #{title.inspect}" - system cmd - end - - # Autotest.add_hook :initialize do |at| - # growl "autotest running", "Started" - # end - - Autotest.add_hook :red do |at| - growl "Tests Failed", "#{at.files_to_test.size} tests failed", 2 - end - - Autotest.add_hook :green do |at| - growl "Tests Passed", "Tests passed", -2 if at.tainted - end - - Autotest.add_hook :all_good do |at| - growl "Tests Passed", "All tests passed", -2 if at.tainted - end -end - Autotest::Rspec.class_eval do # RSpec guys forgot about `libs` in make_test_cmd def make_test_cmd_with_libs(files_to_test) From 89e850cdf4ab6a6547a2f4ead227ffd6838ffdc7 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mislav=20Marohni=C4=87?= Date: Fri, 20 Jun 2008 00:53:09 +0200 Subject: [PATCH 031/168] update manifest --- .manifest | 64 +++++++++++++++++++++++++++++-------------- Rakefile | 4 +-- will_paginate.gemspec | 4 +-- 3 files changed, 47 insertions(+), 25 deletions(-) diff --git a/.manifest b/.manifest index 3e2cc5d06..1fda648a3 100644 --- a/.manifest +++ b/.manifest @@ -15,34 +15,56 @@ lib/will_paginate.rb lib/will_paginate/array.rb lib/will_paginate/collection.rb lib/will_paginate/core_ext.rb -lib/will_paginate/finder.rb +lib/will_paginate/deprecation.rb +lib/will_paginate/finders +lib/will_paginate/finders.rb +lib/will_paginate/finders/active_record.rb +lib/will_paginate/finders/active_resource.rb +lib/will_paginate/finders/base.rb +lib/will_paginate/finders/data_mapper.rb lib/will_paginate/named_scope.rb lib/will_paginate/named_scope_patch.rb lib/will_paginate/version.rb +lib/will_paginate/view_helpers lib/will_paginate/view_helpers.rb +lib/will_paginate/view_helpers/action_view.rb +lib/will_paginate/view_helpers/base.rb +lib/will_paginate/view_helpers/link_renderer.rb +lib/will_paginate/view_helpers/link_renderer_base.rb +spec +spec/collection_spec.rb +spec/console +spec/console_fixtures.rb +spec/database.yml +spec/finders +spec/finders/active_record_spec.rb +spec/finders/active_resource_spec.rb +spec/finders/activerecord_test_connector.rb +spec/finders_spec.rb +spec/fixtures +spec/fixtures/admin.rb +spec/fixtures/developer.rb +spec/fixtures/developers_projects.yml +spec/fixtures/project.rb +spec/fixtures/projects.yml +spec/fixtures/replies.yml +spec/fixtures/reply.rb +spec/fixtures/schema.rb +spec/fixtures/topic.rb +spec/fixtures/topics.yml +spec/fixtures/user.rb +spec/fixtures/users.yml +spec/rcov.opts +spec/spec.opts +spec/spec_helper.rb +spec/tasks.rake +spec/view_helpers +spec/view_helpers/base_spec.rb +spec/view_helpers/link_renderer_base_spec.rb test test/boot.rb -test/collection_test.rb -test/console -test/database.yml -test/finder_test.rb -test/fixtures -test/fixtures/admin.rb -test/fixtures/developer.rb -test/fixtures/developers_projects.yml -test/fixtures/project.rb -test/fixtures/projects.yml -test/fixtures/replies.yml -test/fixtures/reply.rb -test/fixtures/schema.rb -test/fixtures/topic.rb -test/fixtures/topics.yml -test/fixtures/user.rb -test/fixtures/users.yml test/helper.rb test/lib -test/lib/activerecord_test_case.rb -test/lib/activerecord_test_connector.rb -test/lib/load_fixtures.rb test/lib/view_test_process.rb +test/tasks.rake test/view_test.rb \ No newline at end of file diff --git a/Rakefile b/Rakefile index 45ac0d622..da04b3f20 100644 --- a/Rakefile +++ b/Rakefile @@ -48,11 +48,11 @@ task :manifest do spec = File.read spec_file spec.gsub! /^(\s* s.(test_)?files \s* = \s* )( \[ [^\]]* \] | %w\( [^)]* \) )/mx do assignment = $1 - bunch = $2 ? list.grep(/^test\//) : list + bunch = $2 ? list.grep(/^(test|spec)\//) : list '%s%%w(%s)' % [assignment, bunch.join(' ')] end - File.open(spec_file, 'w') {|f| f << spec } + File.open(spec_file, 'w') {|f| f << spec } end File.open('.manifest', 'w') {|f| f << list.join("\n") } end diff --git a/will_paginate.gemspec b/will_paginate.gemspec index aa4d9223a..c427b6bb1 100644 --- a/will_paginate.gemspec +++ b/will_paginate.gemspec @@ -15,6 +15,6 @@ Gem::Specification.new do |s| s.rdoc_options << '--inline-source' << '--charset=UTF-8' s.extra_rdoc_files = ['README.rdoc', 'LICENSE', 'CHANGELOG'] - s.files = %w(CHANGELOG LICENSE README.rdoc Rakefile examples examples/apple-circle.gif examples/index.haml examples/index.html examples/pagination.css examples/pagination.sass init.rb lib lib/will_paginate lib/will_paginate.rb lib/will_paginate/array.rb lib/will_paginate/collection.rb lib/will_paginate/core_ext.rb lib/will_paginate/finder.rb lib/will_paginate/named_scope.rb lib/will_paginate/named_scope_patch.rb lib/will_paginate/version.rb lib/will_paginate/view_helpers.rb test test/boot.rb test/collection_test.rb test/console test/database.yml test/finder_test.rb test/fixtures test/fixtures/admin.rb test/fixtures/developer.rb test/fixtures/developers_projects.yml test/fixtures/project.rb test/fixtures/projects.yml test/fixtures/replies.yml test/fixtures/reply.rb test/fixtures/schema.rb test/fixtures/topic.rb test/fixtures/topics.yml test/fixtures/user.rb test/fixtures/users.yml test/helper.rb test/lib test/lib/activerecord_test_case.rb test/lib/activerecord_test_connector.rb test/lib/load_fixtures.rb test/lib/view_test_process.rb test/view_test.rb) - s.test_files = %w(test/boot.rb test/collection_test.rb test/console test/database.yml test/finder_test.rb test/fixtures test/fixtures/admin.rb test/fixtures/developer.rb test/fixtures/developers_projects.yml test/fixtures/project.rb test/fixtures/projects.yml test/fixtures/replies.yml test/fixtures/reply.rb test/fixtures/schema.rb test/fixtures/topic.rb test/fixtures/topics.yml test/fixtures/user.rb test/fixtures/users.yml test/helper.rb test/lib test/lib/activerecord_test_case.rb test/lib/activerecord_test_connector.rb test/lib/load_fixtures.rb test/lib/view_test_process.rb test/view_test.rb) + s.files = %w(CHANGELOG LICENSE README.rdoc Rakefile examples examples/apple-circle.gif examples/index.haml examples/index.html examples/pagination.css examples/pagination.sass init.rb lib lib/will_paginate lib/will_paginate.rb lib/will_paginate/array.rb lib/will_paginate/collection.rb lib/will_paginate/core_ext.rb lib/will_paginate/deprecation.rb lib/will_paginate/finders lib/will_paginate/finders.rb lib/will_paginate/finders/active_record.rb lib/will_paginate/finders/active_resource.rb lib/will_paginate/finders/base.rb lib/will_paginate/finders/data_mapper.rb lib/will_paginate/named_scope.rb lib/will_paginate/named_scope_patch.rb lib/will_paginate/version.rb lib/will_paginate/view_helpers lib/will_paginate/view_helpers.rb lib/will_paginate/view_helpers/action_view.rb lib/will_paginate/view_helpers/base.rb lib/will_paginate/view_helpers/link_renderer.rb lib/will_paginate/view_helpers/link_renderer_base.rb spec spec/collection_spec.rb spec/console spec/console_fixtures.rb spec/database.yml spec/finders spec/finders/active_record_spec.rb spec/finders/active_resource_spec.rb spec/finders/activerecord_test_connector.rb spec/finders_spec.rb spec/fixtures spec/fixtures/admin.rb spec/fixtures/developer.rb spec/fixtures/developers_projects.yml spec/fixtures/project.rb spec/fixtures/projects.yml spec/fixtures/replies.yml spec/fixtures/reply.rb spec/fixtures/schema.rb spec/fixtures/topic.rb spec/fixtures/topics.yml spec/fixtures/user.rb spec/fixtures/users.yml spec/rcov.opts spec/spec.opts spec/spec_helper.rb spec/tasks.rake spec/view_helpers spec/view_helpers/base_spec.rb spec/view_helpers/link_renderer_base_spec.rb test test/boot.rb test/helper.rb test/lib test/lib/view_test_process.rb test/tasks.rake test/view_test.rb) + s.test_files = %w(spec/collection_spec.rb spec/console spec/console_fixtures.rb spec/database.yml spec/finders spec/finders/active_record_spec.rb spec/finders/active_resource_spec.rb spec/finders/activerecord_test_connector.rb spec/finders_spec.rb spec/fixtures spec/fixtures/admin.rb spec/fixtures/developer.rb spec/fixtures/developers_projects.yml spec/fixtures/project.rb spec/fixtures/projects.yml spec/fixtures/replies.yml spec/fixtures/reply.rb spec/fixtures/schema.rb spec/fixtures/topic.rb spec/fixtures/topics.yml spec/fixtures/user.rb spec/fixtures/users.yml spec/rcov.opts spec/spec.opts spec/spec_helper.rb spec/tasks.rake spec/view_helpers spec/view_helpers/base_spec.rb spec/view_helpers/link_renderer_base_spec.rb test/boot.rb test/helper.rb test/lib test/lib/view_test_process.rb test/tasks.rake test/view_test.rb) end \ No newline at end of file From f9ba6a08c97a74cc783bb02856758956e9e32411 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mislav=20Marohni=C4=87?= Date: Fri, 20 Jun 2008 01:23:02 +0200 Subject: [PATCH 032/168] specs: include_words -> include_phrase --- .autotest | 1 + spec/spec_helper.rb | 10 +++++----- spec/view_helpers/base_spec.rb | 4 ++-- 3 files changed, 8 insertions(+), 7 deletions(-) diff --git a/.autotest b/.autotest index 74090987c..ade45eb05 100644 --- a/.autotest +++ b/.autotest @@ -1,4 +1,5 @@ Autotest.add_hook :initialize do |at| + at.libs = 'lib:spec' at.clear_mappings diff --git a/spec/spec_helper.rb b/spec/spec_helper.rb index be5e918ed..061bbd09a 100644 --- a/spec/spec_helper.rb +++ b/spec/spec_helper.rb @@ -4,8 +4,8 @@ module MyExtras protected - def include_words(string) - WordsInclusionMatcher.new(string) + def include_phrase(string) + PhraseMatcher.new(string) end def collection(params = {}) @@ -25,7 +25,7 @@ def collection(params = {}) config.mock_with :mocha end -class WordsInclusionMatcher +class PhraseMatcher def initialize(string) @string = string @pattern = /\b#{string}\b/ @@ -37,10 +37,10 @@ def matches?(actual) end def failure_message - "expected #{@actual.inspect} to contain words #{@string.inspect}" + "expected #{@actual.inspect} to contain phrase #{@string.inspect}" end def negative_failure_message - "expected #{@actual.inspect} not to contain words #{@string.inspect}" + "expected #{@actual.inspect} not to contain phrase #{@string.inspect}" end end diff --git a/spec/view_helpers/base_spec.rb b/spec/view_helpers/base_spec.rb index 399aee5b7..ed91a9f2f 100644 --- a/spec/view_helpers/base_spec.rb +++ b/spec/view_helpers/base_spec.rb @@ -43,13 +43,13 @@ def info(params, options = {}) end it "should display shortened end results" do - info(:page => 7, :per_page => 4).should include_words('strings 25 - 26') + info(:page => 7, :per_page => 4).should include_phrase('strings 25 - 26') end it "should handle longer class names" do collection = @array.paginate(:page => 2, :per_page => 5) collection.first.stubs(:class).returns(mock('Class', :name => 'ProjectType')) - info(collection).should include_words('project types') + info(collection).should include_phrase('project types') end it "should adjust output for single-page collections" do From 4657f8635e8fe2a48c4a6bfb9c91d89088522989 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mislav=20Marohni=C4=87?= Date: Fri, 20 Jun 2008 01:28:43 +0200 Subject: [PATCH 033/168] move deprecation matcher to spec helper --- spec/spec_helper.rb | 30 ++++++++++++++++++++ spec/view_helpers/link_renderer_base_spec.rb | 29 ------------------- 2 files changed, 30 insertions(+), 29 deletions(-) diff --git a/spec/spec_helper.rb b/spec/spec_helper.rb index 061bbd09a..46a26e5ec 100644 --- a/spec/spec_helper.rb +++ b/spec/spec_helper.rb @@ -4,6 +4,7 @@ module MyExtras protected + def include_phrase(string) PhraseMatcher.new(string) end @@ -15,6 +16,10 @@ def collection(params = {}) end WillPaginate::Collection.new(params[:page] || 1, params[:per_page] || 30, params[:total_entries]) end + + def have_deprecation + DeprecationMatcher.new + end end Spec::Runner.configure do |config| @@ -44,3 +49,28 @@ def negative_failure_message "expected #{@actual.inspect} not to contain phrase #{@string.inspect}" end end + +class DeprecationMatcher + def initialize + @old_behavior = WillPaginate::Deprecation.behavior + @messages = [] + WillPaginate::Deprecation.behavior = lambda { |message, callstack| + @messages << message + } + end + + def matches?(block) + block.call + !@messages.empty? + ensure + WillPaginate::Deprecation.behavior = @old_behavior + end + + def failure_message + "expected block to raise a deprecation warning" + end + + def negative_failure_message + "expected block not to raise deprecation warnings, #{@messages.size} raised" + end +end diff --git a/spec/view_helpers/link_renderer_base_spec.rb b/spec/view_helpers/link_renderer_base_spec.rb index d0e84b201..c6e7ff3c0 100644 --- a/spec/view_helpers/link_renderer_base_spec.rb +++ b/spec/view_helpers/link_renderer_base_spec.rb @@ -91,34 +91,5 @@ def showing_pages(*pages) def prepare(collection_options, options = {}) @renderer.prepare(collection(collection_options), options) end - - def have_deprecation - DeprecationMatcher.new - end end - -class DeprecationMatcher - def initialize - @old_behavior = WillPaginate::Deprecation.behavior - @messages = [] - WillPaginate::Deprecation.behavior = lambda { |message, callstack| - @messages << message - } - end - - def matches?(block) - block.call - !@messages.empty? - ensure - WillPaginate::Deprecation.behavior = @old_behavior - end - - def failure_message - "expected block to raise a deprecation warning" - end - - def negative_failure_message - "expected block not to raise deprecation warnings, #{@messages.size} raised" - end -end \ No newline at end of file From 398ca10cafb838da2c49a2104f1193ec8567a9f1 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mislav=20Marohni=C4=87?= Date: Wed, 27 Aug 2008 23:52:03 +0200 Subject: [PATCH 034/168] using Mocha's `expects` on ArProject sends respond_to? to that class, which tries to connect to the database to query for column_names. Well, you can forget about that, buddy --- spec/finders/active_record_spec.rb | 3 +++ 1 file changed, 3 insertions(+) diff --git a/spec/finders/active_record_spec.rb b/spec/finders/active_record_spec.rb index e5e8337ae..450d13e4d 100644 --- a/spec/finders/active_record_spec.rb +++ b/spec/finders/active_record_spec.rb @@ -3,6 +3,9 @@ require File.dirname(__FILE__) + '/activerecord_test_connector' class ArProject < ActiveRecord::Base + def self.column_names + ["id"] + end end ActiverecordTestConnector.setup From d5ea3c5a9fb7cd6bae9910615946975f9b411072 Mon Sep 17 00:00:00 2001 From: Paul Barry Date: Thu, 28 Aug 2008 00:07:53 +0200 Subject: [PATCH 035/168] Updates to work with DataMapper 0.9.6 --- lib/will_paginate/finders/data_mapper.rb | 16 +++++----------- 1 file changed, 5 insertions(+), 11 deletions(-) diff --git a/lib/will_paginate/finders/data_mapper.rb b/lib/will_paginate/finders/data_mapper.rb index 4f5d3941b..c31c5fb7f 100644 --- a/lib/will_paginate/finders/data_mapper.rb +++ b/lib/will_paginate/finders/data_mapper.rb @@ -1,5 +1,5 @@ require 'will_paginate/finders/base' -require 'data_mapper' +require 'dm-core' module WillPaginate::Finders module DataMapper @@ -13,16 +13,12 @@ def wp_query(options, pager, args, &block) pager.replace all(find_options, &block) unless pager.total_entries - pager.total_entries = wp_count(options) + pager.total_entries = wp_count(options) end end - # Does the not-so-trivial job of finding out the total number of entries - # in the database. It relies on the ActiveRecord +count+ method. - def wp_count(options, args, finder) - excludees = [:count, :order, :limit, :offset, :readonly] - count_options = options.except *excludees - + def wp_count(options) + count_options = options.except(:count, :order) # merge the hash found in :count count_options.update options[:count] if options[:count] @@ -31,6 +27,4 @@ def wp_count(options, args, finder) end end -DataMapper::Base.class_eval do - include WillPaginate::Finders::DataMapper -end +DataMapper::Model.send(:include, WillPaginate::Finders::DataMapper) From a660fdfd487820cadeffdda855fd03b0caae0c3e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mislav=20Marohni=C4=87?= Date: Thu, 28 Aug 2008 01:15:53 +0200 Subject: [PATCH 036/168] prefer send(:include) over class_eval because RDoc (wrongly) catches the latter --- lib/will_paginate.rb | 5 +---- lib/will_paginate/finders.rb | 2 ++ lib/will_paginate/finders/active_record.rb | 6 ++---- lib/will_paginate/view_helpers/action_view.rb | 2 +- 4 files changed, 6 insertions(+), 9 deletions(-) diff --git a/lib/will_paginate.rb b/lib/will_paginate.rb index 77304cb8d..b93d242ca 100644 --- a/lib/will_paginate.rb +++ b/lib/will_paginate.rb @@ -8,7 +8,6 @@ # # Happy paginating! module WillPaginate - # no-op def self.enable Deprecation.warn "WillPaginate::enable() doesn't do anything anymore" end @@ -26,9 +25,7 @@ def self.enable_named_scope(patch = true) require 'will_paginate/named_scope' require 'will_paginate/named_scope_patch' if patch - ActiveRecord::Base.class_eval do - include WillPaginate::NamedScope - end + ActiveRecord::Base.send :include, WillPaginate::NamedScope end end diff --git a/lib/will_paginate/finders.rb b/lib/will_paginate/finders.rb index 24188e0dc..ca41f5b56 100644 --- a/lib/will_paginate/finders.rb +++ b/lib/will_paginate/finders.rb @@ -2,6 +2,8 @@ module WillPaginate # Database logic for different ORMs + # + # See WillPaginate::Finders::Base module Finders end end diff --git a/lib/will_paginate/finders/active_record.rb b/lib/will_paginate/finders/active_record.rb index 2aca60167..fbe3a0180 100644 --- a/lib/will_paginate/finders/active_record.rb +++ b/lib/will_paginate/finders/active_record.rb @@ -186,8 +186,6 @@ class << self classes << a::HasManyThroughAssociation end }.each do |klass| - klass.class_eval do - include WillPaginate::Finders::ActiveRecord - alias_method_chain :method_missing, :paginate - end + klass.send :include, WillPaginate::Finders::ActiveRecord + klass.class_eval { alias_method_chain :method_missing, :paginate } end diff --git a/lib/will_paginate/view_helpers/action_view.rb b/lib/will_paginate/view_helpers/action_view.rb index daf97ad51..52ce278b1 100644 --- a/lib/will_paginate/view_helpers/action_view.rb +++ b/lib/will_paginate/view_helpers/action_view.rb @@ -52,7 +52,7 @@ def paginated_section(*args, &block) end end -ActionView::Base.class_eval { include WillPaginate::ViewHelpers::ActionView } +ActionView::Base.send :include, WillPaginate::ViewHelpers::ActionView if defined?(ActionController::Base) and ActionController::Base.respond_to? :rescue_responses ActionController::Base.rescue_responses['WillPaginate::InvalidPage'] = :not_found From e828dcb9ca1c32199037a397a704d8168f979ffc Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mislav=20Marohni=C4=87?= Date: Sat, 13 Sep 2008 00:19:33 +0200 Subject: [PATCH 037/168] CHANGELOG -> CHANGELOG.rdoc; make a note of commits that I have to port from master --- CHANGELOG => CHANGELOG.rdoc | 7 +++++++ 1 file changed, 7 insertions(+) rename CHANGELOG => CHANGELOG.rdoc (91%) diff --git a/CHANGELOG b/CHANGELOG.rdoc similarity index 91% rename from CHANGELOG rename to CHANGELOG.rdoc index 7a174d70b..0bbea4ec4 100644 --- a/CHANGELOG +++ b/CHANGELOG.rdoc @@ -13,6 +13,13 @@ * created WP::Finders::Base abstract module that implements generic pagination logic * removed dependency to ActiveSupport +=== TODO: + +* f54bc3 Ensure that paginate_by_sql doesn't change the original SQL query. Closes #235 +* 9a9372 rename :prev_label to :previous_label for consistency. old name still functions but is deprecated +* 3c4725 Oops, I used return in an iterator block. I obviously write too much JavaScript +* 537f22 ensure that 'href' values in pagination links are escaped URLs + == 2.3.1, released 2008-05-04 * Fixed page numbers not showing with custom routes and implicit first page From e329e8fe81e030a38dbffac6fb9ae56c5649ba4d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mislav=20Marohni=C4=87?= Date: Sat, 13 Sep 2008 21:45:53 +0200 Subject: [PATCH 038/168] use ActiveSupport::Dependencies instead of just ::Dependencies (cherry picked from commit 94a5eac6d935a8cf3de0eb9ae0fedeaefa97e444) --- spec/finders/activerecord_test_connector.rb | 10 +++++++--- 1 file changed, 7 insertions(+), 3 deletions(-) diff --git a/spec/finders/activerecord_test_connector.rb b/spec/finders/activerecord_test_connector.rb index 8d46afbc9..fdbb23306 100644 --- a/spec/finders/activerecord_test_connector.rb +++ b/spec/finders/activerecord_test_connector.rb @@ -16,16 +16,20 @@ def self.setup unless self.connected || !self.able_to_connect setup_connection load_schema - Dependencies.load_paths.unshift FIXTURES_PATH + add_load_path FIXTURES_PATH self.connected = true end rescue Exception => e # errors from ActiveRecord setup - $stderr.puts "\nSkipping ActiveRecord tests: #{e}" - $stderr.puts "Install SQLite3 to run the full test suite for will_paginate.\n\n" + $stderr.puts "\nSkipping ActiveRecord tests: #{e}\n\n" self.able_to_connect = false end private + + def self.add_load_path(path) + dep = defined?(ActiveSupport::Dependencies) ? ActiveSupport::Dependencies : ::Dependencies + dep.load_paths.unshift path + end def self.setup_connection db = ENV['DB'].blank?? 'sqlite3' : ENV['DB'] From c74329989ebf96be1c7d6b5ea0d24cab8635aceb Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mislav=20Marohni=C4=87?= Date: Sat, 13 Sep 2008 21:51:41 +0200 Subject: [PATCH 039/168] Ensure that paginate_by_sql doesn't change the original SQL query. References #235 (cherry picked from commit f54bc393f184a49ad4ba7d44b304719cf2fc9ba2) --- lib/will_paginate/finders/active_record.rb | 2 +- spec/finders/active_record_spec.rb | 9 +++++++++ 2 files changed, 10 insertions(+), 1 deletion(-) diff --git a/lib/will_paginate/finders/active_record.rb b/lib/will_paginate/finders/active_record.rb index fbe3a0180..121455bba 100644 --- a/lib/will_paginate/finders/active_record.rb +++ b/lib/will_paginate/finders/active_record.rb @@ -54,7 +54,7 @@ module ActiveRecord # def paginate_by_sql(sql, options) WillPaginate::Collection.create(*wp_parse_options(options)) do |pager| - query = sanitize_sql(sql) + query = sanitize_sql(sql.dup) original_query = query.dup # add limit, offset add_limit! query, :offset => pager.offset, :limit => pager.per_page diff --git a/spec/finders/active_record_spec.rb b/spec/finders/active_record_spec.rb index 450d13e4d..8080d192b 100644 --- a/spec/finders/active_record_spec.rb +++ b/spec/finders/active_record_spec.rb @@ -103,6 +103,15 @@ def self.column_names ArProject.paginate_by_sql "sql\n ORDER\nby foo, bar, `baz` ASC", :page => 2 end + + it "shouldn't change the original query string" do + query = 'SQL QUERY' + original_query = query.dup + ArProject.expects(:find_by_sql).returns([]) + + ArProject.paginate_by_sql(query, :page => 1) + query.should == original_query + end end # TODO: counts would still be wrong! From 53c5bfde3733f8d897eeea08f711e7a0228952ab Mon Sep 17 00:00:00 2001 From: Ben Pickles Date: Mon, 9 Jun 2008 10:22:43 +0100 Subject: [PATCH 040/168] Cope with scoped :select when counting. (Cherry-picked from 5adc2de1b9bd2bc90a3852de3b0dff90bb44d58f at master) --- lib/will_paginate/finders/active_record.rb | 12 ++++++++++-- spec/finders/active_record_spec.rb | 8 ++++++++ 2 files changed, 18 insertions(+), 2 deletions(-) diff --git a/lib/will_paginate/finders/active_record.rb b/lib/will_paginate/finders/active_record.rb index 121455bba..00042bbda 100644 --- a/lib/will_paginate/finders/active_record.rb +++ b/lib/will_paginate/finders/active_record.rb @@ -148,10 +148,18 @@ def wp_count(options, args, finder) def wp_parse_count_options(options, klass) excludees = [:count, :order, :limit, :offset, :readonly] - unless options[:select] and options[:select] =~ /^\s*DISTINCT\b/i - # only exclude the select param if it doesn't begin with DISTINCT + # Use :select from scope if it isn't already present. + options[:select] = scope(:find, :select) unless options[:select] + + if options[:select] and options[:select] =~ /^\s*DISTINCT\b/i + # Remove quoting and check for table_name.*-like statement. + if options[:select].gsub('`', '') =~ /\w+\.\*/ + options[:select] = "DISTINCT #{klass.table_name}.#{klass.primary_key}" + end + else excludees << :select end + # count expects (almost) the same options as find count_options = options.except *excludees diff --git a/spec/finders/active_record_spec.rb b/spec/finders/active_record_spec.rb index 8080d192b..206c762d0 100644 --- a/spec/finders/active_record_spec.rb +++ b/spec/finders/active_record_spec.rb @@ -6,6 +6,8 @@ class ArProject < ActiveRecord::Base def self.column_names ["id"] end + + named_scope :distinct, :select => "DISTINCT #{table_name}.*" end ActiverecordTestConnector.setup @@ -73,6 +75,12 @@ def self.column_names ArProject.expects(:count).with(:select => 'DISTINCT salary').returns(0) ArProject.paginate :select => 'DISTINCT salary', :page => 2 end + + it "should count with scoped select when :select => DISTINCT" do + ArProject.stubs(:find).returns([]) + ArProject.expects(:count).with(:select => 'DISTINCT ar_projects.id').returns(0) + ArProject.distinct.paginate :page => 2 + end it "should use :with_foo for scope-out compatibility" do ArProject.expects(:find_best).returns(Array.new(5)) From 7fa1da2040e32b43659a34975e9ec64e3fbe6df5 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mislav=20Marohni=C4=87?= Date: Sat, 13 Sep 2008 22:20:52 +0200 Subject: [PATCH 041/168] update TODO in the changelog so it's clear what I didn't do yet --- CHANGELOG.rdoc | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/CHANGELOG.rdoc b/CHANGELOG.rdoc index 0bbea4ec4..e5b69ac15 100644 --- a/CHANGELOG.rdoc +++ b/CHANGELOG.rdoc @@ -15,7 +15,9 @@ === TODO: -* f54bc3 Ensure that paginate_by_sql doesn't change the original SQL query. Closes #235 +* Make a concrete implementation of LinkRendererBase that will generate HTML for both ActionView and Merb +* Finish transition from view tests -> specs +* ActionView and Merb integration tests for view helpers * 9a9372 rename :prev_label to :previous_label for consistency. old name still functions but is deprecated * 3c4725 Oops, I used return in an iterator block. I obviously write too much JavaScript * 537f22 ensure that 'href' values in pagination links are escaped URLs From 59966586cb4c37a9e6c2b7612334e07085c14e64 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mislav=20Marohni=C4=87?= Date: Tue, 7 Oct 2008 11:32:59 +0200 Subject: [PATCH 042/168] fixed paginate(:from) with Rails versions < 2.1 (references #244) --- lib/will_paginate/finders/active_record.rb | 5 +++++ spec/finders/active_record_spec.rb | 15 +++++++++++++++ 2 files changed, 20 insertions(+) diff --git a/lib/will_paginate/finders/active_record.rb b/lib/will_paginate/finders/active_record.rb index 00042bbda..622b48893 100644 --- a/lib/will_paginate/finders/active_record.rb +++ b/lib/will_paginate/finders/active_record.rb @@ -148,6 +148,11 @@ def wp_count(options, args, finder) def wp_parse_count_options(options, klass) excludees = [:count, :order, :limit, :offset, :readonly] + unless ::ActiveRecord::Calculations::CALCULATIONS_OPTIONS.include?(:from) + # :from parameter wasn't supported in count() before this change + excludees << :from + end + # Use :select from scope if it isn't already present. options[:select] = scope(:find, :select) unless options[:select] diff --git a/spec/finders/active_record_spec.rb b/spec/finders/active_record_spec.rb index 206c762d0..2e87cc1f1 100644 --- a/spec/finders/active_record_spec.rb +++ b/spec/finders/active_record_spec.rb @@ -162,6 +162,21 @@ def self.column_names options.should == options_before end + if ::ActiveRecord::Calculations::CALCULATIONS_OPTIONS.include?(:from) + # for ActiveRecord 2.1 and newer + it "keeps the :from parameter in count" do + ArProject.expects(:find).returns([1]) + ArProject.expects(:count).with {|options| options.key?(:from) }.returns(0) + ArProject.paginate(:page => 2, :per_page => 1, :from => 'projects') + end + else + it "excludes :from parameter from count" do + ArProject.expects(:find).returns([1]) + ArProject.expects(:count).with {|options| !options.key?(:from) }.returns(0) + ArProject.paginate(:page => 2, :per_page => 1, :from => 'projects') + end + end + if ActiverecordTestConnector.able_to_connect fixtures :topics, :replies, :users, :projects, :developers_projects From 7d87c7813093f05a85cbe63621f282b9b34a91de Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mislav=20Marohni=C4=87?= Date: Thu, 9 Oct 2008 00:12:33 +0200 Subject: [PATCH 043/168] move named_scope to appropriate subdir. enable named_scope in tests by default --- lib/will_paginate.rb | 4 ++-- lib/will_paginate/{ => finders/active_record}/named_scope.rb | 0 .../{ => finders/active_record}/named_scope_patch.rb | 0 spec/finders/active_record_spec.rb | 3 +++ 4 files changed, 5 insertions(+), 2 deletions(-) rename lib/will_paginate/{ => finders/active_record}/named_scope.rb (100%) rename lib/will_paginate/{ => finders/active_record}/named_scope_patch.rb (100%) diff --git a/lib/will_paginate.rb b/lib/will_paginate.rb index b93d242ca..dad53e5c6 100644 --- a/lib/will_paginate.rb +++ b/lib/will_paginate.rb @@ -22,8 +22,8 @@ def self.enable # your models, but not through associations. def self.enable_named_scope(patch = true) return if defined? ActiveRecord::NamedScope - require 'will_paginate/named_scope' - require 'will_paginate/named_scope_patch' if patch + require 'will_paginate/finders/active_record/named_scope' + require 'will_paginate/finders/active_record/named_scope_patch' if patch ActiveRecord::Base.send :include, WillPaginate::NamedScope end diff --git a/lib/will_paginate/named_scope.rb b/lib/will_paginate/finders/active_record/named_scope.rb similarity index 100% rename from lib/will_paginate/named_scope.rb rename to lib/will_paginate/finders/active_record/named_scope.rb diff --git a/lib/will_paginate/named_scope_patch.rb b/lib/will_paginate/finders/active_record/named_scope_patch.rb similarity index 100% rename from lib/will_paginate/named_scope_patch.rb rename to lib/will_paginate/finders/active_record/named_scope_patch.rb diff --git a/spec/finders/active_record_spec.rb b/spec/finders/active_record_spec.rb index 2e87cc1f1..48866e1df 100644 --- a/spec/finders/active_record_spec.rb +++ b/spec/finders/active_record_spec.rb @@ -2,6 +2,9 @@ require 'will_paginate/finders/active_record' require File.dirname(__FILE__) + '/activerecord_test_connector' +require 'will_paginate' +WillPaginate::enable_named_scope + class ArProject < ActiveRecord::Base def self.column_names ["id"] From e93bf7ade4b8966fadbef57b368fd7159fda24e1 Mon Sep 17 00:00:00 2001 From: Ken Collins Date: Mon, 29 Sep 2008 12:32:02 -0400 Subject: [PATCH 044/168] Update latest named scope from rails 2.1.1 --- .../finders/active_record/named_scope.rb | 58 +++++++++++++++---- 1 file changed, 48 insertions(+), 10 deletions(-) diff --git a/lib/will_paginate/finders/active_record/named_scope.rb b/lib/will_paginate/finders/active_record/named_scope.rb index 6f00cf76a..21fc168e4 100644 --- a/lib/will_paginate/finders/active_record/named_scope.rb +++ b/lib/will_paginate/finders/active_record/named_scope.rb @@ -1,27 +1,22 @@ -## stolen from: http://dev.rubyonrails.org/browser/trunk/activerecord/lib/active_record/named_scope.rb?rev=9084 - module WillPaginate # This is a feature backported from Rails 2.1 because of its usefullness not only with will_paginate, # but in other aspects when managing complex conditions that you want to be reusable. module NamedScope # All subclasses of ActiveRecord::Base have two named_scopes: # * all, which is similar to a find(:all) query, and - # * scoped, which allows for the creation of anonymous scopes, on the fly: - # - # Shirt.scoped(:conditions => {:color => 'red'}).scoped(:include => :washing_instructions) + # * scoped, which allows for the creation of anonymous scopes, on the fly: Shirt.scoped(:conditions => {:color => 'red'}).scoped(:include => :washing_instructions) # # These anonymous scopes tend to be useful when procedurally generating complex queries, where passing # intermediate values (scopes) around as first-class objects is convenient. def self.included(base) base.class_eval do extend ClassMethods - named_scope :all named_scope :scoped, lambda { |scope| scope } end end module ClassMethods - def scopes #:nodoc: + def scopes read_inheritable_attribute(:scopes) || write_inheritable_attribute(:scopes, {}) end @@ -46,7 +41,7 @@ def scopes #:nodoc: # Nested finds and calculations also work with these compositions: Shirt.red.dry_clean_only.count returns the number of garments # for which these criteria obtain. Similarly with Shirt.red.dry_clean_only.average(:thread_count). # - # All scopes are available as class methods on the ActiveRecord descendent upon which the scopes were defined. But they are also available to + # All scopes are available as class methods on the ActiveRecord::Base descendent upon which the scopes were defined. But they are also available to # has_many associations. If, # # class Person < ActiveRecord::Base @@ -76,7 +71,20 @@ def scopes #:nodoc: # end # end # + # + # For testing complex named scopes, you can examine the scoping options using the + # proxy_options method on the proxy itself. + # + # class Shirt < ActiveRecord::Base + # named_scope :colored, lambda { |color| + # { :conditions => { :color => color } } + # } + # end + # + # expected_options = { :conditions => { :colored => 'red' } } + # assert_equal expected_options, Shirt.colored('red').proxy_options def named_scope(name, options = {}, &block) + name = name.to_sym scopes[name] = lambda do |parent_scope, *args| Scope.new(parent_scope, case options when Hash @@ -93,9 +101,15 @@ def named_scope(name, options = {}, &block) end end - class Scope #:nodoc: + class Scope attr_reader :proxy_scope, :proxy_options - [].methods.each { |m| delegate m, :to => :proxy_found unless m =~ /(^__|^nil\?|^send|class|extend|find|count|sum|average|maximum|minimum|paginate)/ } + + [].methods.each do |m| + unless m =~ /(^__|^nil\?|^send|^object_id$|class|extend|^find$|count|sum|average|maximum|minimum|paginate|first|last|empty\?|respond_to\?)/ + delegate m, :to => :proxy_found + end + end + delegate :scopes, :with_scope, :to => :proxy_scope def initialize(proxy_scope, options, &block) @@ -108,6 +122,30 @@ def reload load_found; self end + def first(*args) + if args.first.kind_of?(Integer) || (@found && !args.first.kind_of?(Hash)) + proxy_found.first(*args) + else + find(:first, *args) + end + end + + def last(*args) + if args.first.kind_of?(Integer) || (@found && !args.first.kind_of?(Hash)) + proxy_found.last(*args) + else + find(:last, *args) + end + end + + def empty? + @found ? @found.empty? : count.zero? + end + + def respond_to?(method, include_private = false) + super || @proxy_scope.respond_to?(method, include_private) + end + protected def proxy_found @found || load_found From 311af041838a62cea22af02b8ba82075f6bc408b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mislav=20Marohni=C4=87?= Date: Fri, 10 Oct 2008 11:48:54 +0200 Subject: [PATCH 045/168] adjust the view test framework to rspec and port the first test --- spec/view_helpers/action_view_spec.rb | 167 ++++++++++++++++++++++++++ test/view_test.rb | 13 -- 2 files changed, 167 insertions(+), 13 deletions(-) create mode 100644 spec/view_helpers/action_view_spec.rb diff --git a/spec/view_helpers/action_view_spec.rb b/spec/view_helpers/action_view_spec.rb new file mode 100644 index 000000000..18295afd4 --- /dev/null +++ b/spec/view_helpers/action_view_spec.rb @@ -0,0 +1,167 @@ +require 'spec_helper' +require 'action_controller' +require 'action_controller/assertions/selector_assertions' +require 'will_paginate/view_helpers/action_view' +require 'will_paginate/collection' + +ActionController::Routing::Routes.draw do |map| + map.connect 'dummy/page/:page', :controller => 'dummy' + map.connect 'dummy/dots/page.:page', :controller => 'dummy', :action => 'dots' + map.connect 'ibocorp/:page', :controller => 'ibocorp', + :requirements => { :page => /\d+/ }, + :defaults => { :page => 1 } + + map.connect ':controller/:action/:id' +end + +describe WillPaginate::ViewHelpers::ActionView do + before(:each) do + @view = ActionView::Base.new + @view.controller = DummyController.new + @view.request = @view.controller.request + @template = '<%= will_paginate collection, options %>' + end + + include ActionController::Assertions::SelectorAssertions + + it "should render" do + paginate do |pagination| + assert_select 'a[href]', 3 do |elements| + validate_page_numbers [2,3,2], elements + assert_select elements.last, ':last-child', "Next »" + end + assert_select 'span', 2 + assert_select 'span.disabled:first-child', '« Previous' + assert_select 'span.current', '1' + pagination.first.inner_text.should == '« Previous 1 2 3 Next »' + end + end + + def assert(value, message) + raise message unless value + end + + def paginate(collection = {}, options = {}, &block) + if collection.instance_of? Hash + page_options = { :page => 1, :total_entries => 11, :per_page => 4 }.merge(collection) + collection = [1].paginate(page_options) + end + + locals = { :collection => collection, :options => options } + + @render_output = @view.render(:inline => @template, :locals => locals) + + if block_given? + classname = options[:class] || WillPaginate::ViewHelpers.pagination_options[:class] + assert_select("div.#{classname}", 1, 'no main DIV', &block) + end + end + + def html_document + @html_document ||= HTML::Document.new(@render_output, true, false) + end + + def response_from_page_or_rjs + html_document.root + end + + def validate_page_numbers(expected, links, param_name = :page) + param_pattern = /\W#{CGI.escape(param_name.to_s)}=([^&]*)/ + + links.map { |e| + e['href'] =~ param_pattern + $1 ? $1.to_i : $1 + }.should == expected + end + + def assert_links_match(pattern, links = nil, numbers = nil) + links ||= assert_select 'div.pagination a[href]' do |elements| + elements + end + + pages = [] if numbers + + links.each do |el| + el['href'].should =~ pattern + if numbers + el['href'] =~ pattern + pages << ($1.nil?? nil : $1.to_i) + end + end + + pages.should == numbers if numbers + end + + def assert_no_links_match(pattern) + assert_select 'div.pagination a[href]' do |elements| + elements.each do |el| + el['href'] !~ pattern + end + end + end +end + +class DummyController + attr_reader :request + attr_accessor :controller_name + + def initialize + @request = DummyRequest.new + @url = ActionController::UrlRewriter.new(@request, @request.params) + end + + def params + @request.params + end + + def url_for(params) + @url.rewrite(params) + end +end + +class DummyRequest + attr_accessor :symbolized_path_parameters + + def initialize + @get = true + @params = {} + @symbolized_path_parameters = { :controller => 'foo', :action => 'bar' } + end + + def get? + @get + end + + def post + @get = false + end + + def relative_url_root + '' + end + + def params(more = nil) + @params.update(more) if more + @params + end +end + +module HTML + Node.class_eval do + def inner_text + children.map(&:inner_text).join('') + end + end + + Text.class_eval do + def inner_text + self.to_s + end + end + + Tag.class_eval do + def inner_text + childless?? '' : super + end + end +end diff --git a/test/view_test.rb b/test/view_test.rb index 3cfeef40c..4c40b123e 100644 --- a/test/view_test.rb +++ b/test/view_test.rb @@ -16,19 +16,6 @@ class ViewTest < WillPaginate::ViewTestCase ## basic pagination ## - def test_will_paginate - paginate do |pagination| - assert_select 'a[href]', 3 do |elements| - validate_page_numbers [2,3,2], elements - assert_select elements.last, ':last-child', "Next »" - end - assert_select 'span', 2 - assert_select 'span.disabled:first-child', '« Previous' - assert_select 'span.current', '1' - assert_equal '« Previous 1 2 3 Next »', pagination.first.inner_text - end - end - def test_no_pagination_when_page_count_is_one paginate :per_page => 30 assert_equal '', @html_result From 31da60d49a9e7ad3d0963b7c29324d22ba9cb689 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mislav=20Marohni=C4=87?= Date: Fri, 10 Oct 2008 12:40:53 +0200 Subject: [PATCH 046/168] extract reusable view spec helpers to ViewExampleGroup --- spec/view_helpers/action_view_spec.rb | 87 +-------------------- spec/view_helpers/view_example_group.rb | 100 ++++++++++++++++++++++++ 2 files changed, 103 insertions(+), 84 deletions(-) create mode 100644 spec/view_helpers/view_example_group.rb diff --git a/spec/view_helpers/action_view_spec.rb b/spec/view_helpers/action_view_spec.rb index 18295afd4..c0943b72d 100644 --- a/spec/view_helpers/action_view_spec.rb +++ b/spec/view_helpers/action_view_spec.rb @@ -1,6 +1,6 @@ require 'spec_helper' require 'action_controller' -require 'action_controller/assertions/selector_assertions' +require 'view_helpers/view_example_group' require 'will_paginate/view_helpers/action_view' require 'will_paginate/collection' @@ -22,8 +22,6 @@ @template = '<%= will_paginate collection, options %>' end - include ActionController::Assertions::SelectorAssertions - it "should render" do paginate do |pagination| assert_select 'a[href]', 3 do |elements| @@ -37,67 +35,8 @@ end end - def assert(value, message) - raise message unless value - end - - def paginate(collection = {}, options = {}, &block) - if collection.instance_of? Hash - page_options = { :page => 1, :total_entries => 11, :per_page => 4 }.merge(collection) - collection = [1].paginate(page_options) - end - - locals = { :collection => collection, :options => options } - - @render_output = @view.render(:inline => @template, :locals => locals) - - if block_given? - classname = options[:class] || WillPaginate::ViewHelpers.pagination_options[:class] - assert_select("div.#{classname}", 1, 'no main DIV', &block) - end - end - - def html_document - @html_document ||= HTML::Document.new(@render_output, true, false) - end - - def response_from_page_or_rjs - html_document.root - end - - def validate_page_numbers(expected, links, param_name = :page) - param_pattern = /\W#{CGI.escape(param_name.to_s)}=([^&]*)/ - - links.map { |e| - e['href'] =~ param_pattern - $1 ? $1.to_i : $1 - }.should == expected - end - - def assert_links_match(pattern, links = nil, numbers = nil) - links ||= assert_select 'div.pagination a[href]' do |elements| - elements - end - - pages = [] if numbers - - links.each do |el| - el['href'].should =~ pattern - if numbers - el['href'] =~ pattern - pages << ($1.nil?? nil : $1.to_i) - end - end - - pages.should == numbers if numbers - end - - def assert_no_links_match(pattern) - assert_select 'div.pagination a[href]' do |elements| - elements.each do |el| - el['href'] !~ pattern - end - end + def render(locals) + @view.render(:inline => @template, :locals => locals) end end @@ -145,23 +84,3 @@ def params(more = nil) @params end end - -module HTML - Node.class_eval do - def inner_text - children.map(&:inner_text).join('') - end - end - - Text.class_eval do - def inner_text - self.to_s - end - end - - Tag.class_eval do - def inner_text - childless?? '' : super - end - end -end diff --git a/spec/view_helpers/view_example_group.rb b/spec/view_helpers/view_example_group.rb new file mode 100644 index 000000000..0f2bc1b58 --- /dev/null +++ b/spec/view_helpers/view_example_group.rb @@ -0,0 +1,100 @@ +unless $:.find { |p| p =~ %r{/html-scanner$} } + unless actionpack_path = $:.find { |p| p =~ %r{/actionpack(-[\d.]+)?/lib$} } + raise "cannot find ActionPack in load paths" + end + html_scanner_path = "#{actionpack_path}/action_controller/vendor/html-scanner" + $:.unshift(html_scanner_path) +end + +require 'action_controller/assertions/selector_assertions' + +class ViewExampleGroup < Spec::Example::ExampleGroup + + include ActionController::Assertions::SelectorAssertions + + def assert(value, message) + raise message unless value + end + + def paginate(collection = {}, options = {}, &block) + if collection.instance_of? Hash + page_options = { :page => 1, :total_entries => 11, :per_page => 4 }.merge(collection) + collection = [1].paginate(page_options) + end + + locals = { :collection => collection, :options => options } + + @render_output = render(locals) + + if block_given? + classname = options[:class] || WillPaginate::ViewHelpers.pagination_options[:class] + assert_select("div.#{classname}", 1, 'no main DIV', &block) + end + end + + def html_document + @html_document ||= HTML::Document.new(@render_output, true, false) + end + + def response_from_page_or_rjs + html_document.root + end + + def validate_page_numbers(expected, links, param_name = :page) + param_pattern = /\W#{CGI.escape(param_name.to_s)}=([^&]*)/ + + links.map { |e| + e['href'] =~ param_pattern + $1 ? $1.to_i : $1 + }.should == expected + end + + def assert_links_match(pattern, links = nil, numbers = nil) + links ||= assert_select 'div.pagination a[href]' do |elements| + elements + end + + pages = [] if numbers + + links.each do |el| + el['href'].should =~ pattern + if numbers + el['href'] =~ pattern + pages << ($1.nil?? nil : $1.to_i) + end + end + + pages.should == numbers if numbers + end + + def assert_no_links_match(pattern) + assert_select 'div.pagination a[href]' do |elements| + elements.each do |el| + el['href'] !~ pattern + end + end + end + +end + +Spec::Example::ExampleGroupFactory.register(:view_helpers, ViewExampleGroup) + +module HTML + Node.class_eval do + def inner_text + children.map(&:inner_text).join('') + end + end + + Text.class_eval do + def inner_text + self.to_s + end + end + + Tag.class_eval do + def inner_text + childless?? '' : super + end + end +end From e6c09213ff70e345e5a0cc409a749532876f44bc Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mislav=20Marohni=C4=87?= Date: Fri, 10 Oct 2008 13:03:18 +0200 Subject: [PATCH 047/168] continue porting tests -> specs; ported over tests in the "basic" section --- spec/view_helpers/action_view_spec.rb | 84 ++++++++++++++++++++++++- spec/view_helpers/view_example_group.rb | 3 + test/view_test.rb | 79 ----------------------- 3 files changed, 84 insertions(+), 82 deletions(-) diff --git a/spec/view_helpers/action_view_spec.rb b/spec/view_helpers/action_view_spec.rb index c0943b72d..ef220d8bf 100644 --- a/spec/view_helpers/action_view_spec.rb +++ b/spec/view_helpers/action_view_spec.rb @@ -22,6 +22,12 @@ @template = '<%= will_paginate collection, options %>' end + def render(locals) + @view.render(:inline => @template, :locals => locals) + end + + ## basic pagination ## + it "should render" do paginate do |pagination| assert_select 'a[href]', 3 do |elements| @@ -34,9 +40,81 @@ pagination.first.inner_text.should == '« Previous 1 2 3 Next »' end end - - def render(locals) - @view.render(:inline => @template, :locals => locals) + + it "should render nothing when there is only 1 page" do + paginate(:per_page => 30).should be_empty + end + + it "should paginate with options" do + paginate({ :page => 2 }, :class => 'will_paginate', :prev_label => 'Prev', :next_label => 'Next') do + assert_select 'a[href]', 4 do |elements| + validate_page_numbers [1,1,3,3], elements + # test rel attribute values: + assert_select elements[1], 'a', '1' do |link| + link.first['rel'].should == 'prev start' + end + assert_select elements.first, 'a', "Prev" do |link| + link.first['rel'].should == 'prev start' + end + assert_select elements.last, 'a', "Next" do |link| + link.first['rel'].should == 'next' + end + end + assert_select 'span.current', '2' + end + end + + it "should paginate using a custom renderer class" do + paginate({}, :renderer => AdditionalLinkAttributesRenderer) do + assert_select 'a[default=true]', 3 + end + end + + it "should paginate using a custom renderer instance" do + renderer = WillPaginate::ViewHelpers::LinkRenderer.new + renderer.gap_marker = '~~' + + paginate({ :per_page => 2 }, :inner_window => 0, :outer_window => 0, :renderer => renderer) do + assert_select 'span.my-gap', '~~' + end + + renderer = AdditionalLinkAttributesRenderer.new(:title => 'rendered') + paginate({}, :renderer => renderer) do + assert_select 'a[title=rendered]', 3 + end + end + + it "should have classnames on previous/next links" do + paginate do |pagination| + assert_select 'span.disabled.prev_page:first-child' + assert_select 'a.next_page[href]:last-child' + end + end + + it "should match expected markup" do + paginate + expected = <<-HTML + + HTML + expected.strip!.gsub!(/\s{2,}/, ' ') + expected_dom = HTML::Document.new(expected).root + + html_document.root.should == expected_dom + end +end + +class AdditionalLinkAttributesRenderer < WillPaginate::ViewHelpers::LinkRenderer + def initialize(link_attributes = nil) + super() + @additional_link_attributes = link_attributes || { :default => 'true' } + end + + def page_link(page, text, attributes = {}) + @template.link_to text, url_for(page), attributes.merge(@additional_link_attributes) end end diff --git a/spec/view_helpers/view_example_group.rb b/spec/view_helpers/view_example_group.rb index 0f2bc1b58..96c46ae4f 100644 --- a/spec/view_helpers/view_example_group.rb +++ b/spec/view_helpers/view_example_group.rb @@ -25,11 +25,14 @@ def paginate(collection = {}, options = {}, &block) locals = { :collection => collection, :options => options } @render_output = render(locals) + @html_document = nil if block_given? classname = options[:class] || WillPaginate::ViewHelpers.pagination_options[:class] assert_select("div.#{classname}", 1, 'no main DIV', &block) end + + @render_output end def html_document diff --git a/test/view_test.rb b/test/view_test.rb index 4c40b123e..46c2b5f72 100644 --- a/test/view_test.rb +++ b/test/view_test.rb @@ -1,87 +1,8 @@ require 'helper' require 'lib/view_test_process' -class AdditionalLinkAttributesRenderer < WillPaginate::ViewHelpers::LinkRenderer - def initialize(link_attributes = nil) - super() - @additional_link_attributes = link_attributes || { :default => 'true' } - end - - def page_link(page, text, attributes = {}) - @template.link_to text, url_for(page), attributes.merge(@additional_link_attributes) - end -end - class ViewTest < WillPaginate::ViewTestCase - ## basic pagination ## - - def test_no_pagination_when_page_count_is_one - paginate :per_page => 30 - assert_equal '', @html_result - end - - def test_will_paginate_with_options - paginate({ :page => 2 }, - :class => 'will_paginate', :prev_label => 'Prev', :next_label => 'Next') do - assert_select 'a[href]', 4 do |elements| - validate_page_numbers [1,1,3,3], elements - # test rel attribute values: - assert_select elements[1], 'a', '1' do |link| - assert_equal 'prev start', link.first['rel'] - end - assert_select elements.first, 'a', "Prev" do |link| - assert_equal 'prev start', link.first['rel'] - end - assert_select elements.last, 'a', "Next" do |link| - assert_equal 'next', link.first['rel'] - end - end - assert_select 'span.current', '2' - end - end - - def test_will_paginate_using_renderer_class - paginate({}, :renderer => AdditionalLinkAttributesRenderer) do - assert_select 'a[default=true]', 3 - end - end - - def test_will_paginate_using_renderer_instance - renderer = WillPaginate::ViewHelpers::LinkRenderer.new - renderer.gap_marker = '~~' - - paginate({ :per_page => 2 }, :inner_window => 0, :outer_window => 0, :renderer => renderer) do - assert_select 'span.my-gap', '~~' - end - - renderer = AdditionalLinkAttributesRenderer.new(:title => 'rendered') - paginate({}, :renderer => renderer) do - assert_select 'a[title=rendered]', 3 - end - end - - def test_prev_next_links_have_classnames - paginate do |pagination| - assert_select 'span.disabled.prev_page:first-child' - assert_select 'a.next_page[href]:last-child' - end - end - - def test_full_output - paginate - expected = <<-HTML - - HTML - expected.strip!.gsub!(/\s{2,}/, ' ') - - assert_dom_equal expected, @html_result - end - ## advanced options for pagination ## def test_will_paginate_without_container From a025efcce39c236dd454810c4589c517a120a810 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mislav=20Marohni=C4=87?= Date: Fri, 10 Oct 2008 13:09:44 +0200 Subject: [PATCH 048/168] port tests for advanced options with will_paginate --- spec/view_helpers/action_view_spec.rb | 46 +++++++++++++++++++++++++++ test/view_test.rb | 46 --------------------------- 2 files changed, 46 insertions(+), 46 deletions(-) diff --git a/spec/view_helpers/action_view_spec.rb b/spec/view_helpers/action_view_spec.rb index ef220d8bf..4fbc2de13 100644 --- a/spec/view_helpers/action_view_spec.rb +++ b/spec/view_helpers/action_view_spec.rb @@ -105,6 +105,52 @@ def render(locals) html_document.root.should == expected_dom end + + ## advanced options for pagination ## + + it "should be able to render without container" do + paginate({}, :container => false) + assert_select 'div.pagination', 0, 'main DIV present when it shouldn\'t' + assert_select 'a[href]', 3 + end + + it "should be able to render without page links" do + paginate({ :page => 2 }, :page_links => false) do + assert_select 'a[href]', 2 do |elements| + validate_page_numbers [1,3], elements + end + end + end + + it "should have magic HTML ID for the container" do + paginate do |div| + div.first['id'].should be_nil + end + + # magic ID + paginate({}, :id => true) do |div| + div.first['id'].should == 'fixnums_pagination' + end + + # explicit ID + paginate({}, :id => 'custom_id') do |div| + div.first['id'].should == 'custom_id' + end + end + + ## other helpers ## + + it "should render a paginated section" do + @template = <<-ERB + <% paginated_section collection, options do %> + <%= content_tag :div, '', :id => "developers" %> + <% end %> + ERB + + paginate + assert_select 'div.pagination', 2 + assert_select 'div.pagination + div#developers', 1 + end end class AdditionalLinkAttributesRenderer < WillPaginate::ViewHelpers::LinkRenderer diff --git a/test/view_test.rb b/test/view_test.rb index 46c2b5f72..b30bcf37f 100644 --- a/test/view_test.rb +++ b/test/view_test.rb @@ -3,52 +3,6 @@ class ViewTest < WillPaginate::ViewTestCase - ## advanced options for pagination ## - - def test_will_paginate_without_container - paginate({}, :container => false) - assert_select 'div.pagination', 0, 'main DIV present when it shouldn\'t' - assert_select 'a[href]', 3 - end - - def test_will_paginate_without_page_links - paginate({ :page => 2 }, :page_links => false) do - assert_select 'a[href]', 2 do |elements| - validate_page_numbers [1,3], elements - end - end - end - - def test_container_id - paginate do |div| - assert_nil div.first['id'] - end - - # magic ID - paginate({}, :id => true) do |div| - assert_equal 'fixnums_pagination', div.first['id'] - end - - # explicit ID - paginate({}, :id => 'custom_id') do |div| - assert_equal 'custom_id', div.first['id'] - end - end - - ## other helpers ## - - def test_paginated_section - @template = <<-ERB - <% paginated_section collection, options do %> - <%= content_tag :div, '', :id => "developers" %> - <% end %> - ERB - - paginate - assert_select 'div.pagination', 2 - assert_select 'div.pagination + div#developers', 1 - end - ## parameter handling in page links ## def test_will_paginate_preserves_parameters_on_get From b2650f4f72d6c1f83b780effec2cf9b85b2209d5 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mislav=20Marohni=C4=87?= Date: Fri, 10 Oct 2008 13:23:25 +0200 Subject: [PATCH 049/168] finish porting tests -> specs --- spec/view_helpers/action_view_spec.rb | 115 ++++++++++++++++++++++++++ test/view_test.rb | 113 ------------------------- 2 files changed, 115 insertions(+), 113 deletions(-) diff --git a/spec/view_helpers/action_view_spec.rb b/spec/view_helpers/action_view_spec.rb index 4fbc2de13..f19273f7e 100644 --- a/spec/view_helpers/action_view_spec.rb +++ b/spec/view_helpers/action_view_spec.rb @@ -22,6 +22,10 @@ @template = '<%= will_paginate collection, options %>' end + def request + @view.request + end + def render(locals) @view.render(:inline => @template, :locals => locals) end @@ -151,6 +155,117 @@ def render(locals) assert_select 'div.pagination', 2 assert_select 'div.pagination + div#developers', 1 end + + ## parameter handling in page links ## + + it "should preserve parameters on GET" do + request.params :foo => { :bar => 'baz' } + paginate + assert_links_match /foo%5Bbar%5D=baz/ + end + + it "should not preserve parameters on POST" do + request.post + request.params :foo => 'bar' + paginate + assert_no_links_match /foo=bar/ + end + + it "should add additional parameters to links" do + paginate({}, :params => { :foo => 'bar' }) + assert_links_match /foo=bar/ + end + + it "should add anchor parameter" do + paginate({}, :params => { :anchor => 'anchor' }) + assert_links_match /#anchor$/ + end + + it "should remove arbitrary parameters" do + request.params :foo => 'bar' + paginate({}, :params => { :foo => nil }) + assert_no_links_match /foo=bar/ + end + + it "should override default route parameters" do + paginate({}, :params => { :controller => 'baz', :action => 'list' }) + assert_links_match %r{\Wbaz/list\W} + end + + it "should paginate with custom page parameter" do + paginate({ :page => 2 }, :param_name => :developers_page) do + assert_select 'a[href]', 4 do |elements| + validate_page_numbers [1,1,3,3], elements, :developers_page + end + end + end + + it "should paginate with complex custom page parameter" do + request.params :developers => { :page => 2 } + + paginate({ :page => 2 }, :param_name => 'developers[page]') do + assert_select 'a[href]', 4 do |links| + assert_links_match /\?developers%5Bpage%5D=\d+$/, links + validate_page_numbers [1,1,3,3], links, 'developers[page]' + end + end + end + + it "should paginate with custom route page parameter" do + request.symbolized_path_parameters.update :controller => 'dummy', :action => nil + paginate :per_page => 2 do + assert_select 'a[href]', 6 do |links| + assert_links_match %r{/page/(\d+)$}, links, [2, 3, 4, 5, 6, 2] + end + end + end + + it "should paginate with custom route with dot separator page parameter" do + request.symbolized_path_parameters.update :controller => 'dummy', :action => 'dots' + paginate :per_page => 2 do + assert_select 'a[href]', 6 do |links| + assert_links_match %r{/page\.(\d+)$}, links, [2, 3, 4, 5, 6, 2] + end + end + end + + it "should paginate with custom route and first page number implicit" do + request.symbolized_path_parameters.update :controller => 'ibocorp', :action => nil + paginate :page => 2, :per_page => 2 do + assert_select 'a[href]', 7 do |links| + assert_links_match %r{/ibocorp(?:/(\d+))?$}, links, [nil, nil, 3, 4, 5, 6, 3] + end + end + end + + ## internal hardcore stuff ## + + it "should be able to guess the collection name" do + collection = mock + collection.expects(:total_pages).returns(1) + + @template = '<%= will_paginate options %>' + @view.controller.controller_name = 'developers' + @view.assigns['developers'] = collection + + paginate(nil) + end + + it "should fail if the inferred collection is nil" do + @template = '<%= will_paginate options %>' + @view.controller.controller_name = 'developers' + + lambda { + paginate(nil) + }.should raise_error(ArgumentError, /@developers/) + end + + if ActionController::Base.respond_to? :rescue_responses + # only on Rails 2 + it "should set rescue response hook" do + ActionController::Base.rescue_responses['WillPaginate::InvalidPage'].should == :not_found + end + end end class AdditionalLinkAttributesRenderer < WillPaginate::ViewHelpers::LinkRenderer diff --git a/test/view_test.rb b/test/view_test.rb index b30bcf37f..f214001be 100644 --- a/test/view_test.rb +++ b/test/view_test.rb @@ -3,119 +3,6 @@ class ViewTest < WillPaginate::ViewTestCase - ## parameter handling in page links ## - def test_will_paginate_preserves_parameters_on_get - @request.params :foo => { :bar => 'baz' } - paginate - assert_links_match /foo%5Bbar%5D=baz/ - end - - def test_will_paginate_doesnt_preserve_parameters_on_post - @request.post - @request.params :foo => 'bar' - paginate - assert_no_links_match /foo=bar/ - end - - def test_adding_additional_parameters - paginate({}, :params => { :foo => 'bar' }) - assert_links_match /foo=bar/ - end - - def test_adding_anchor_parameter - paginate({}, :params => { :anchor => 'anchor' }) - assert_links_match /#anchor$/ - end - - def test_removing_arbitrary_parameters - @request.params :foo => 'bar' - paginate({}, :params => { :foo => nil }) - assert_no_links_match /foo=bar/ - end - - def test_adding_additional_route_parameters - paginate({}, :params => { :controller => 'baz', :action => 'list' }) - assert_links_match %r{\Wbaz/list\W} - end - - def test_will_paginate_with_custom_page_param - paginate({ :page => 2 }, :param_name => :developers_page) do - assert_select 'a[href]', 4 do |elements| - validate_page_numbers [1,1,3,3], elements, :developers_page - end - end - end - - def test_complex_custom_page_param - @request.params :developers => { :page => 2 } - - paginate({ :page => 2 }, :param_name => 'developers[page]') do - assert_select 'a[href]', 4 do |links| - assert_links_match /\?developers%5Bpage%5D=\d+$/, links - validate_page_numbers [1,1,3,3], links, 'developers[page]' - end - end - end - - def test_custom_routing_page_param - @request.symbolized_path_parameters.update :controller => 'dummy', :action => nil - paginate :per_page => 2 do - assert_select 'a[href]', 6 do |links| - assert_links_match %r{/page/(\d+)$}, links, [2, 3, 4, 5, 6, 2] - end - end - end - - def test_custom_routing_page_param_with_dot_separator - @request.symbolized_path_parameters.update :controller => 'dummy', :action => 'dots' - paginate :per_page => 2 do - assert_select 'a[href]', 6 do |links| - assert_links_match %r{/page\.(\d+)$}, links, [2, 3, 4, 5, 6, 2] - end - end - end - - def test_custom_routing_with_first_page_hidden - @request.symbolized_path_parameters.update :controller => 'ibocorp', :action => nil - paginate :page => 2, :per_page => 2 do - assert_select 'a[href]', 7 do |links| - assert_links_match %r{/ibocorp(?:/(\d+))?$}, links, [nil, nil, 3, 4, 5, 6, 3] - end - end - end - - ## internal hardcore stuff ## - - uses_mocha 'view internals' do - def test_collection_name_can_be_guessed - collection = mock - collection.expects(:total_pages).returns(1) - - @template = '<%= will_paginate options %>' - @controller.controller_name = 'developers' - @view.assigns['developers'] = collection - - paginate(nil) - end - end - - def test_inferred_collection_name_raises_error_when_nil - @template = '<%= will_paginate options %>' - @controller.controller_name = 'developers' - - e = assert_raise ArgumentError do - paginate(nil) - end - assert e.message.include?('@developers') - end - - if ActionController::Base.respond_to? :rescue_responses - # only on Rails 2 - def test_rescue_response_hook_presence - assert_equal :not_found, - ActionController::Base.rescue_responses['WillPaginate::InvalidPage'] - end - end end From 9f471b14f4161e243170ad826824f52a94e54665 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mislav=20Marohni=C4=87?= Date: Fri, 10 Oct 2008 13:25:45 +0200 Subject: [PATCH 050/168] delete test/ directory and old framework inside it. make "spec" the default rake task --- Rakefile | 5 +- test/boot.rb | 20 ----- test/helper.rb | 37 -------- test/lib/view_test_process.rb | 164 ---------------------------------- test/tasks.rake | 56 ------------ test/view_test.rb | 8 -- 6 files changed, 2 insertions(+), 288 deletions(-) delete mode 100644 test/boot.rb delete mode 100644 test/helper.rb delete mode 100644 test/lib/view_test_process.rb delete mode 100644 test/tasks.rake delete mode 100644 test/view_test.rb diff --git a/Rakefile b/Rakefile index da04b3f20..81672f63a 100644 --- a/Rakefile +++ b/Rakefile @@ -7,11 +7,10 @@ rescue LoadError require 'rake' require 'rake/rdoctask' end -load 'test/tasks.rake' load 'spec/tasks.rake' -desc 'Default: run unit tests.' -task :default => :test +desc 'Default: run specs.' +task :default => :spec desc 'Generate RDoc documentation for the will_paginate plugin.' Rake::RDocTask.new(:rdoc) do |rdoc| diff --git a/test/boot.rb b/test/boot.rb deleted file mode 100644 index 654621a03..000000000 --- a/test/boot.rb +++ /dev/null @@ -1,20 +0,0 @@ -plugin_root = File.join(File.dirname(__FILE__), '..') -version = ENV['RAILS_VERSION'] -version = nil if version and version == "" - -# first look for a symlink to a copy of the framework -if !version and framework_root = ["#{plugin_root}/rails", "#{plugin_root}/../../rails"].find { |p| File.directory? p } - puts "found framework root: #{framework_root}" - # this allows for a plugin to be tested outside of an app and without Rails gems - $:.unshift "#{framework_root}/activesupport/lib", "#{framework_root}/actionpack/lib" -else - # simply use installed gems if available - puts "using Rails#{version ? ' ' + version : nil} gems" - require 'rubygems' - - if version - gem 'rails', version - else - gem 'actionpack' - end -end diff --git a/test/helper.rb b/test/helper.rb deleted file mode 100644 index 8b054872a..000000000 --- a/test/helper.rb +++ /dev/null @@ -1,37 +0,0 @@ -require 'test/unit' -require 'rubygems' - -# gem install redgreen for colored test output -begin require 'redgreen'; rescue LoadError; end - -require 'boot' unless defined?(ActionView) - -class Test::Unit::TestCase - protected - def assert_respond_to_all object, methods - methods.each do |method| - [method.to_s, method.to_sym].each { |m| assert_respond_to object, m } - end - end - - def collect_deprecations - old_behavior = WillPaginate::Deprecation.behavior - deprecations = [] - WillPaginate::Deprecation.behavior = Proc.new do |message, callstack| - deprecations << message - end - result = yield - [result, deprecations] - ensure - WillPaginate::Deprecation.behavior = old_behavior - end -end - -# Wrap tests that use Mocha and skip if unavailable. -def uses_mocha(test_name) - require 'mocha' unless Object.const_defined?(:Mocha) -rescue LoadError => load_error - $stderr.puts "Skipping #{test_name} tests. `gem install mocha` and try again." -else - yield -end diff --git a/test/lib/view_test_process.rb b/test/lib/view_test_process.rb deleted file mode 100644 index f474c6599..000000000 --- a/test/lib/view_test_process.rb +++ /dev/null @@ -1,164 +0,0 @@ -require 'action_controller' -require 'action_controller/test_process' - -require 'will_paginate/view_helpers/action_view' - -ActionController::Routing::Routes.draw do |map| - map.connect 'dummy/page/:page', :controller => 'dummy' - map.connect 'dummy/dots/page.:page', :controller => 'dummy', :action => 'dots' - map.connect 'ibocorp/:page', :controller => 'ibocorp', - :requirements => { :page => /\d+/ }, - :defaults => { :page => 1 } - - map.connect ':controller/:action/:id' -end - -ActionController::Base.perform_caching = false - -class WillPaginate::ViewTestCase < Test::Unit::TestCase - def setup - super - @controller = DummyController.new - @request = @controller.request - @html_result = nil - @template = '<%= will_paginate collection, options %>' - - @view = ActionView::Base.new - @view.assigns['controller'] = @controller - @view.assigns['_request'] = @request - @view.assigns['_params'] = @request.params - end - - def test_no_complain; end - - protected - - def paginate(collection = {}, options = {}, &block) - if collection.instance_of? Hash - page_options = { :page => 1, :total_entries => 11, :per_page => 4 }.merge(collection) - collection = [1].paginate(page_options) - end - - locals = { :collection => collection, :options => options } - - if defined? ActionView::InlineTemplate - # Rails 2.1 - args = [ ActionView::InlineTemplate.new(@view, @template, locals) ] - else - # older Rails versions - args = [nil, @template, nil, locals] - end - - @html_result = @view.render_template(*args) - @html_document = HTML::Document.new(@html_result, true, false) - - if block_given? - classname = options[:class] || WillPaginate::ViewHelpers.pagination_options[:class] - assert_select("div.#{classname}", 1, 'no main DIV', &block) - end - end - - def response_from_page_or_rjs - @html_document.root - end - - def validate_page_numbers expected, links, param_name = :page - param_pattern = /\W#{CGI.escape(param_name.to_s)}=([^&]*)/ - - assert_equal(expected, links.map { |e| - e['href'] =~ param_pattern - $1 ? $1.to_i : $1 - }) - end - - def assert_links_match pattern, links = nil, numbers = nil - links ||= assert_select 'div.pagination a[href]' do |elements| - elements - end - - pages = [] if numbers - - links.each do |el| - assert_match pattern, el['href'] - if numbers - el['href'] =~ pattern - pages << ($1.nil?? nil : $1.to_i) - end - end - - assert_equal numbers, pages, "page numbers don't match" if numbers - end - - def assert_no_links_match pattern - assert_select 'div.pagination a[href]' do |elements| - elements.each do |el| - assert_no_match pattern, el['href'] - end - end - end -end - -class DummyRequest - attr_accessor :symbolized_path_parameters - - def initialize - @get = true - @params = {} - @symbolized_path_parameters = { :controller => 'foo', :action => 'bar' } - end - - def get? - @get - end - - def post - @get = false - end - - def relative_url_root - '' - end - - def params(more = nil) - @params.update(more) if more - @params - end -end - -class DummyController - attr_reader :request - attr_accessor :controller_name - - def initialize - @request = DummyRequest.new - @url = ActionController::UrlRewriter.new(@request, @request.params) - end - - def params - @request.params - end - - def url_for(params) - @url.rewrite(params) - end -end - -module HTML - Node.class_eval do - def inner_text - children.map(&:inner_text).join('') - end - end - - Text.class_eval do - def inner_text - self.to_s - end - end - - Tag.class_eval do - def inner_text - childless?? '' : super - end - end -end diff --git a/test/tasks.rake b/test/tasks.rake deleted file mode 100644 index 4b2de3b88..000000000 --- a/test/tasks.rake +++ /dev/null @@ -1,56 +0,0 @@ -require 'rake/testtask' - -desc 'Test the will_paginate plugin.' -Rake::TestTask.new(:test) do |t| - t.pattern = 'test/**/*_test.rb' - t.verbose = true - t.libs << 'test' -end - -# I want to specify environment variables at call time -class EnvTestTask < Rake::TestTask - attr_accessor :env - - def ruby(*args) - env.each { |key, value| ENV[key] = value } if env - super - env.keys.each { |key| ENV.delete key } if env - end -end - -for configuration in %w( sqlite3 mysql postgres ) - EnvTestTask.new("test_#{configuration}") do |t| - t.pattern = 'test/finder_test.rb' - t.verbose = true - t.env = { 'DB' => configuration } - t.libs << 'test' - end -end - -task :test_databases => %w(test_mysql test_sqlite3 test_postgres) - -desc %{Test everything on SQLite3, MySQL and PostgreSQL} -task :test_full => %w(test test_mysql test_postgres) - -desc %{Test everything with Rails 1.2.x and 2.0.x gems} -task :test_all do - all = Rake::Task['test_full'] - ENV['RAILS_VERSION'] = '~>1.2.6' - all.invoke - # reset the invoked flag - %w( test_full test test_mysql test_postgres ).each do |name| - Rake::Task[name].instance_variable_set '@already_invoked', false - end - # do it again - ENV['RAILS_VERSION'] = '~>2.0.2' - all.invoke -end - -task :rcov do - excludes = %w( lib/will_paginate/named_scope* - lib/will_paginate/core_ext.rb - lib/will_paginate.rb - rails* ) - - system %[rcov -Itest:lib test/*.rb -x #{excludes.join(',')}] -end diff --git a/test/view_test.rb b/test/view_test.rb deleted file mode 100644 index f214001be..000000000 --- a/test/view_test.rb +++ /dev/null @@ -1,8 +0,0 @@ -require 'helper' -require 'lib/view_test_process' - -class ViewTest < WillPaginate::ViewTestCase - - - -end From e0bebbbb1bc54bb05a559fe5c21d55b74ff5ed6d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mislav=20Marohni=C4=87?= Date: Fri, 10 Oct 2008 13:50:15 +0200 Subject: [PATCH 051/168] rename :prev_label to :previous_label for consistency. old name still functions but is deprecated --- CHANGELOG.rdoc | 2 -- lib/will_paginate/view_helpers.rb | 25 +++++++++---------- lib/will_paginate/view_helpers/base.rb | 7 +++++- .../view_helpers/link_renderer.rb | 2 +- spec/view_helpers/action_view_spec.rb | 10 +++++++- spec/view_helpers/view_example_group.rb | 8 ++++++ 6 files changed, 36 insertions(+), 18 deletions(-) diff --git a/CHANGELOG.rdoc b/CHANGELOG.rdoc index e5b69ac15..829c0bbdd 100644 --- a/CHANGELOG.rdoc +++ b/CHANGELOG.rdoc @@ -16,9 +16,7 @@ === TODO: * Make a concrete implementation of LinkRendererBase that will generate HTML for both ActionView and Merb -* Finish transition from view tests -> specs * ActionView and Merb integration tests for view helpers -* 9a9372 rename :prev_label to :previous_label for consistency. old name still functions but is deprecated * 3c4725 Oops, I used return in an iterator block. I obviously write too much JavaScript * 537f22 ensure that 'href' values in pagination links are escaped URLs diff --git a/lib/will_paginate/view_helpers.rb b/lib/will_paginate/view_helpers.rb index 83dfd1a27..fe55011ba 100644 --- a/lib/will_paginate/view_helpers.rb +++ b/lib/will_paginate/view_helpers.rb @@ -14,7 +14,7 @@ module WillPaginate # WillPaginate::ViewHelpers.pagination_options hash. You can write to this hash to # override default options on the global level: # - # WillPaginate::ViewHelpers.pagination_options[:prev_label] = 'Previous page' + # WillPaginate::ViewHelpers.pagination_options[:previous_label] = 'Previous page' # # By putting this into your environment.rb you can easily translate link texts to previous # and next pages, as well as override some other defaults to your liking. @@ -22,19 +22,18 @@ module ViewHelpers def self.pagination_options() @pagination_options; end def self.pagination_options=(value) @pagination_options = value; end - # default options that can be overridden on the global level self.pagination_options = { - :class => 'pagination', - :prev_label => '« Previous', - :next_label => 'Next »', - :inner_window => 4, # links around the current page - :outer_window => 1, # links around beginning and end - :separator => ' ', # single space is friendly to spiders and non-graphic browsers - :param_name => :page, - :params => nil, - :renderer => 'WillPaginate::ViewHelpers::LinkRenderer', - :page_links => true, - :container => true + :class => 'pagination', + :previous_label => '« Previous', + :next_label => 'Next »', + :inner_window => 4, # links around the current page + :outer_window => 1, # links around beginning and end + :separator => ' ', # single space is friendly to spiders and non-graphic browsers + :param_name => :page, + :params => nil, + :renderer => 'WillPaginate::ViewHelpers::LinkRenderer', + :page_links => true, + :container => true } def self.total_pages_for_collection(collection) #:nodoc: diff --git a/lib/will_paginate/view_helpers/base.rb b/lib/will_paginate/view_helpers/base.rb index cb4d8c6d8..2fcc0d276 100644 --- a/lib/will_paginate/view_helpers/base.rb +++ b/lib/will_paginate/view_helpers/base.rb @@ -9,7 +9,7 @@ module Base # # ==== Options # * :class -- CSS class name for the generated DIV (default: "pagination") - # * :prev_label -- default: "« Previous" + # * :previous_label -- default: "« Previous" # * :next_label -- default: "Next »" # * :inner_window -- how many links are shown around the current page (default: 4) # * :outer_window -- how many links are around the first and the last page (default: 1) @@ -54,6 +54,11 @@ def will_paginate(collection, options = {}) options = WillPaginate::ViewHelpers.pagination_options.merge(options) + if options[:prev_label] + WillPaginate::Deprecation::warn(":prev_label view parameter is now :previous_label; the old name has been deprecated.") + options[:previous_label] = options.delete(:prev_label) + end + # get the renderer instance renderer = case options[:renderer] when String diff --git a/lib/will_paginate/view_helpers/link_renderer.rb b/lib/will_paginate/view_helpers/link_renderer.rb index 1a2cefba4..60454e77c 100644 --- a/lib/will_paginate/view_helpers/link_renderer.rb +++ b/lib/will_paginate/view_helpers/link_renderer.rb @@ -28,7 +28,7 @@ def prepare(collection, options, template) def to_html links = @options[:page_links] ? windowed_links : [] # previous/next buttons - links.unshift page_link_or_span(@collection.previous_page, 'disabled prev_page', @options[:prev_label]) + links.unshift page_link_or_span(@collection.previous_page, 'disabled prev_page', @options[:previous_label]) links.push page_link_or_span(@collection.next_page, 'disabled next_page', @options[:next_label]) html = links.join(@options[:separator]) diff --git a/spec/view_helpers/action_view_spec.rb b/spec/view_helpers/action_view_spec.rb index f19273f7e..5dc855e25 100644 --- a/spec/view_helpers/action_view_spec.rb +++ b/spec/view_helpers/action_view_spec.rb @@ -50,7 +50,7 @@ def render(locals) end it "should paginate with options" do - paginate({ :page => 2 }, :class => 'will_paginate', :prev_label => 'Prev', :next_label => 'Next') do + paginate({ :page => 2 }, :class => 'will_paginate', :previous_label => 'Prev', :next_label => 'Next') do assert_select 'a[href]', 4 do |elements| validate_page_numbers [1,1,3,3], elements # test rel attribute values: @@ -94,6 +94,14 @@ def render(locals) assert_select 'a.next_page[href]:last-child' end end + + it "should warn about :prev_label being deprecated" do + lambda { + paginate({ :page => 2 }, :prev_label => 'Deprecated') do + assert_select 'a[href]:first-child', 'Deprecated' + end + }.should have_deprecation + end it "should match expected markup" do paginate diff --git a/spec/view_helpers/view_example_group.rb b/spec/view_helpers/view_example_group.rb index 96c46ae4f..cdeb0b1d6 100644 --- a/spec/view_helpers/view_example_group.rb +++ b/spec/view_helpers/view_example_group.rb @@ -78,6 +78,14 @@ def assert_no_links_match(pattern) end end + def build_message(message, pattern, *args) + built_message = pattern.dup + for value in args + built_message.sub! '?', value.inspect + end + built_message + end + end Spec::Example::ExampleGroupFactory.register(:view_helpers, ViewExampleGroup) From f3cd8879b4428485dc9ae104d3927b8b13d0c25b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mislav=20Marohni=C4=87?= Date: Fri, 10 Oct 2008 13:51:55 +0200 Subject: [PATCH 052/168] update the list of files --- .manifest | 16 ++++++---------- will_paginate.gemspec | 4 ++-- 2 files changed, 8 insertions(+), 12 deletions(-) diff --git a/.manifest b/.manifest index 1fda648a3..aca08eee3 100644 --- a/.manifest +++ b/.manifest @@ -1,4 +1,4 @@ -CHANGELOG +CHANGELOG.rdoc LICENSE README.rdoc Rakefile @@ -18,12 +18,13 @@ lib/will_paginate/core_ext.rb lib/will_paginate/deprecation.rb lib/will_paginate/finders lib/will_paginate/finders.rb +lib/will_paginate/finders/active_record lib/will_paginate/finders/active_record.rb +lib/will_paginate/finders/active_record/named_scope.rb +lib/will_paginate/finders/active_record/named_scope_patch.rb lib/will_paginate/finders/active_resource.rb lib/will_paginate/finders/base.rb lib/will_paginate/finders/data_mapper.rb -lib/will_paginate/named_scope.rb -lib/will_paginate/named_scope_patch.rb lib/will_paginate/version.rb lib/will_paginate/view_helpers lib/will_paginate/view_helpers.rb @@ -59,12 +60,7 @@ spec/spec.opts spec/spec_helper.rb spec/tasks.rake spec/view_helpers +spec/view_helpers/action_view_spec.rb spec/view_helpers/base_spec.rb spec/view_helpers/link_renderer_base_spec.rb -test -test/boot.rb -test/helper.rb -test/lib -test/lib/view_test_process.rb -test/tasks.rake -test/view_test.rb \ No newline at end of file +spec/view_helpers/view_example_group.rb \ No newline at end of file diff --git a/will_paginate.gemspec b/will_paginate.gemspec index c427b6bb1..29acd7640 100644 --- a/will_paginate.gemspec +++ b/will_paginate.gemspec @@ -15,6 +15,6 @@ Gem::Specification.new do |s| s.rdoc_options << '--inline-source' << '--charset=UTF-8' s.extra_rdoc_files = ['README.rdoc', 'LICENSE', 'CHANGELOG'] - s.files = %w(CHANGELOG LICENSE README.rdoc Rakefile examples examples/apple-circle.gif examples/index.haml examples/index.html examples/pagination.css examples/pagination.sass init.rb lib lib/will_paginate lib/will_paginate.rb lib/will_paginate/array.rb lib/will_paginate/collection.rb lib/will_paginate/core_ext.rb lib/will_paginate/deprecation.rb lib/will_paginate/finders lib/will_paginate/finders.rb lib/will_paginate/finders/active_record.rb lib/will_paginate/finders/active_resource.rb lib/will_paginate/finders/base.rb lib/will_paginate/finders/data_mapper.rb lib/will_paginate/named_scope.rb lib/will_paginate/named_scope_patch.rb lib/will_paginate/version.rb lib/will_paginate/view_helpers lib/will_paginate/view_helpers.rb lib/will_paginate/view_helpers/action_view.rb lib/will_paginate/view_helpers/base.rb lib/will_paginate/view_helpers/link_renderer.rb lib/will_paginate/view_helpers/link_renderer_base.rb spec spec/collection_spec.rb spec/console spec/console_fixtures.rb spec/database.yml spec/finders spec/finders/active_record_spec.rb spec/finders/active_resource_spec.rb spec/finders/activerecord_test_connector.rb spec/finders_spec.rb spec/fixtures spec/fixtures/admin.rb spec/fixtures/developer.rb spec/fixtures/developers_projects.yml spec/fixtures/project.rb spec/fixtures/projects.yml spec/fixtures/replies.yml spec/fixtures/reply.rb spec/fixtures/schema.rb spec/fixtures/topic.rb spec/fixtures/topics.yml spec/fixtures/user.rb spec/fixtures/users.yml spec/rcov.opts spec/spec.opts spec/spec_helper.rb spec/tasks.rake spec/view_helpers spec/view_helpers/base_spec.rb spec/view_helpers/link_renderer_base_spec.rb test test/boot.rb test/helper.rb test/lib test/lib/view_test_process.rb test/tasks.rake test/view_test.rb) - s.test_files = %w(spec/collection_spec.rb spec/console spec/console_fixtures.rb spec/database.yml spec/finders spec/finders/active_record_spec.rb spec/finders/active_resource_spec.rb spec/finders/activerecord_test_connector.rb spec/finders_spec.rb spec/fixtures spec/fixtures/admin.rb spec/fixtures/developer.rb spec/fixtures/developers_projects.yml spec/fixtures/project.rb spec/fixtures/projects.yml spec/fixtures/replies.yml spec/fixtures/reply.rb spec/fixtures/schema.rb spec/fixtures/topic.rb spec/fixtures/topics.yml spec/fixtures/user.rb spec/fixtures/users.yml spec/rcov.opts spec/spec.opts spec/spec_helper.rb spec/tasks.rake spec/view_helpers spec/view_helpers/base_spec.rb spec/view_helpers/link_renderer_base_spec.rb test/boot.rb test/helper.rb test/lib test/lib/view_test_process.rb test/tasks.rake test/view_test.rb) + s.files = %w(CHANGELOG.rdoc LICENSE README.rdoc Rakefile examples examples/apple-circle.gif examples/index.haml examples/index.html examples/pagination.css examples/pagination.sass init.rb lib lib/will_paginate lib/will_paginate.rb lib/will_paginate/array.rb lib/will_paginate/collection.rb lib/will_paginate/core_ext.rb lib/will_paginate/deprecation.rb lib/will_paginate/finders lib/will_paginate/finders.rb lib/will_paginate/finders/active_record lib/will_paginate/finders/active_record.rb lib/will_paginate/finders/active_record/named_scope.rb lib/will_paginate/finders/active_record/named_scope_patch.rb lib/will_paginate/finders/active_resource.rb lib/will_paginate/finders/base.rb lib/will_paginate/finders/data_mapper.rb lib/will_paginate/version.rb lib/will_paginate/view_helpers lib/will_paginate/view_helpers.rb lib/will_paginate/view_helpers/action_view.rb lib/will_paginate/view_helpers/base.rb lib/will_paginate/view_helpers/link_renderer.rb lib/will_paginate/view_helpers/link_renderer_base.rb spec spec/collection_spec.rb spec/console spec/console_fixtures.rb spec/database.yml spec/finders spec/finders/active_record_spec.rb spec/finders/active_resource_spec.rb spec/finders/activerecord_test_connector.rb spec/finders_spec.rb spec/fixtures spec/fixtures/admin.rb spec/fixtures/developer.rb spec/fixtures/developers_projects.yml spec/fixtures/project.rb spec/fixtures/projects.yml spec/fixtures/replies.yml spec/fixtures/reply.rb spec/fixtures/schema.rb spec/fixtures/topic.rb spec/fixtures/topics.yml spec/fixtures/user.rb spec/fixtures/users.yml spec/rcov.opts spec/spec.opts spec/spec_helper.rb spec/tasks.rake spec/view_helpers spec/view_helpers/action_view_spec.rb spec/view_helpers/base_spec.rb spec/view_helpers/link_renderer_base_spec.rb spec/view_helpers/view_example_group.rb) + s.test_files = %w(spec/collection_spec.rb spec/console spec/console_fixtures.rb spec/database.yml spec/finders spec/finders/active_record_spec.rb spec/finders/active_resource_spec.rb spec/finders/activerecord_test_connector.rb spec/finders_spec.rb spec/fixtures spec/fixtures/admin.rb spec/fixtures/developer.rb spec/fixtures/developers_projects.yml spec/fixtures/project.rb spec/fixtures/projects.yml spec/fixtures/replies.yml spec/fixtures/reply.rb spec/fixtures/schema.rb spec/fixtures/topic.rb spec/fixtures/topics.yml spec/fixtures/user.rb spec/fixtures/users.yml spec/rcov.opts spec/spec.opts spec/spec_helper.rb spec/tasks.rake spec/view_helpers spec/view_helpers/action_view_spec.rb spec/view_helpers/base_spec.rb spec/view_helpers/link_renderer_base_spec.rb spec/view_helpers/view_example_group.rb) end \ No newline at end of file From 065fa41c326c1203ad1ccd6d80462ce061bd8e9a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mislav=20Marohni=C4=87?= Date: Sun, 12 Oct 2008 03:03:48 +0200 Subject: [PATCH 053/168] remove the cludgy URL generation optimization --- .../view_helpers/link_renderer.rb | 46 ++++++------------- 1 file changed, 13 insertions(+), 33 deletions(-) diff --git a/lib/will_paginate/view_helpers/link_renderer.rb b/lib/will_paginate/view_helpers/link_renderer.rb index 60454e77c..ec7a755e1 100644 --- a/lib/will_paginate/view_helpers/link_renderer.rb +++ b/lib/will_paginate/view_helpers/link_renderer.rb @@ -84,41 +84,21 @@ def page_span(page, text, attributes = {}) # Returns URL params for +page_link_or_span+, taking the current GET params # and :params option into account. def url_for(page) - page_one = page == 1 - unless @url_string and !page_one - @url_params = { :escape => false } - # page links should preserve GET parameters - stringified_merge @url_params, @template.params if @template.request.get? - stringified_merge @url_params, @options[:params] if @options[:params] - - if complex = param_name.index(/[^\w-]/) - page_param = (defined?(CGIMethods) ? CGIMethods : ActionController::AbstractRequest). - parse_query_parameters("#{param_name}=#{page}") - - stringified_merge @url_params, page_param - else - @url_params[param_name] = page_one ? 1 : 2 - end - - url = @template.url_for(@url_params) - return url if page_one + url_params = { :escape => false } + # page links should preserve GET parameters + stringified_merge url_params, @template.params if @template.request.get? + stringified_merge url_params, @options[:params] if @options[:params] + + if complex = param_name.index(/[^\w-]/) + page_param = (defined?(CGIMethods) ? CGIMethods : ActionController::AbstractRequest). + parse_query_parameters("#{param_name}=#{page}") - if complex - @url_string = url.sub(%r!([?&]#{CGI.escape param_name}=)#{page}!, '\1@') - return url - else - @url_string = url - @url_params[param_name] = 3 - @template.url_for(@url_params).split(//).each_with_index do |char, i| - if char == '3' and url[i, 1] == '2' - @url_string[i] = '@' - break - end - end - end + stringified_merge url_params, page_param + else + url_params[param_name] = page end - # finally! - @url_string.sub '@', page.to_s + + @template.url_for url_params end private From c90a1683e58bcd848e17ca168a3efb4b84550825 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mislav=20Marohni=C4=87?= Date: Mon, 12 May 2008 13:48:11 +0200 Subject: [PATCH 054/168] ensure that 'href' values in pagination links are escaped URLs this is a cherry-pick of 537f22c1432f3d03100927f07e9acdb5d64998ad --- lib/will_paginate/view_helpers/link_renderer.rb | 2 +- spec/view_helpers/action_view_spec.rb | 10 ++++++++++ 2 files changed, 11 insertions(+), 1 deletion(-) diff --git a/lib/will_paginate/view_helpers/link_renderer.rb b/lib/will_paginate/view_helpers/link_renderer.rb index ec7a755e1..7a5140251 100644 --- a/lib/will_paginate/view_helpers/link_renderer.rb +++ b/lib/will_paginate/view_helpers/link_renderer.rb @@ -84,7 +84,7 @@ def page_span(page, text, attributes = {}) # Returns URL params for +page_link_or_span+, taking the current GET params # and :params option into account. def url_for(page) - url_params = { :escape => false } + url_params = { } # page links should preserve GET parameters stringified_merge url_params, @template.params if @template.request.get? stringified_merge url_params, @options[:params] if @options[:params] diff --git a/spec/view_helpers/action_view_spec.rb b/spec/view_helpers/action_view_spec.rb index 5dc855e25..e0a585e42 100644 --- a/spec/view_helpers/action_view_spec.rb +++ b/spec/view_helpers/action_view_spec.rb @@ -118,6 +118,16 @@ def render(locals) html_document.root.should == expected_dom end + it "should output escaped URLs" do + paginate({:page => 1, :per_page => 1, :total_entries => 2}, + :page_links => false, :params => { :tag => '
    ' }) + + assert_select 'a[href]', 1 do |links| + query = links.first['href'].split('?', 2)[1] + query.split('&').sort.should == %w(page=2 tag=%3Cbr%3E) + end + end + ## advanced options for pagination ## it "should be able to render without container" do From 1562c3e868e1fec3c3a7566689cf7accae9a374d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mislav=20Marohni=C4=87?= Date: Sun, 12 Oct 2008 04:13:31 +0200 Subject: [PATCH 055/168] remove gap logic from HTML link renderer; make an abstract pagination definition in LinkRendererBase --- .../view_helpers/link_renderer.rb | 13 --------- .../view_helpers/link_renderer_base.rb | 29 +++++++++++-------- spec/view_helpers/link_renderer_base_spec.rb | 19 ++++++------ 3 files changed, 27 insertions(+), 34 deletions(-) diff --git a/lib/will_paginate/view_helpers/link_renderer.rb b/lib/will_paginate/view_helpers/link_renderer.rb index 7a5140251..898807eb4 100644 --- a/lib/will_paginate/view_helpers/link_renderer.rb +++ b/lib/will_paginate/view_helpers/link_renderer.rb @@ -49,19 +49,6 @@ def html_attributes protected - # Collects link items for visible page numbers. - def windowed_links - prev = nil - - visible_page_numbers.inject [] do |links, n| - # detect gaps: - links << gap_marker if prev and n > prev + 1 - links << page_link_or_span(n, 'current') - prev = n - links - end - end - def page_link_or_span(page, span_class, text = nil) text ||= page.to_s diff --git a/lib/will_paginate/view_helpers/link_renderer_base.rb b/lib/will_paginate/view_helpers/link_renderer_base.rb index ae689c3c9..09514c334 100644 --- a/lib/will_paginate/view_helpers/link_renderer_base.rb +++ b/lib/will_paginate/view_helpers/link_renderer_base.rb @@ -6,13 +6,6 @@ module ViewHelpers # links. It is used by +will_paginate+ helper internally. class LinkRendererBase - # The gap in page links - attr_accessor :gap_marker - - def initialize - @gap_marker = '...' - end - # * +collection+ is a WillPaginate::Collection instance or any other object # that conforms to that API # * +options+ are forwarded from +will_paginate+ view helper @@ -24,11 +17,17 @@ def prepare(collection, options) @total_pages = @param_name = nil end - protected + def pagination + items = @options[:page_links] ? windowed_page_numbers : [] + items.unshift :previous_page + items.push :next_page + end + protected + # Calculates visible page numbers using the :inner_window and # :outer_window options. - def visible_page_numbers + def windowed_page_numbers inner_window, outer_window = @options[:inner_window].to_i, @options[:outer_window].to_i window_from = current_page - inner_window window_to = current_page + inner_window @@ -47,9 +46,15 @@ def visible_page_numbers visible = (1..total_pages).to_a left_gap = (2 + outer_window)...window_from right_gap = (window_to + 1)...(total_pages - outer_window) - visible -= left_gap.to_a if left_gap.last - left_gap.first > 1 - visible -= right_gap.to_a if right_gap.last - right_gap.first > 1 - + + # replace page numbers that shouldn't be visible with `:gap` + [right_gap, left_gap].each do |gap| + if (gap.last - gap.first) > 1 + visible -= gap.to_a + visible.insert(gap.first - 1, :gap) + end + end + visible end diff --git a/spec/view_helpers/link_renderer_base_spec.rb b/spec/view_helpers/link_renderer_base_spec.rb index c6e7ff3c0..a85ef8978 100644 --- a/spec/view_helpers/link_renderer_base_spec.rb +++ b/spec/view_helpers/link_renderer_base_spec.rb @@ -13,10 +13,6 @@ class LegacyCollection < WillPaginate::Collection @renderer = WillPaginate::ViewHelpers::LinkRendererBase.new end - it "should have '...' as default gap marker" do - @renderer.gap_marker.should == '...' - end - it "should raise error when unprepared" do lambda { @renderer.send :param_name @@ -53,10 +49,15 @@ class LegacyCollection < WillPaginate::Collection @renderer.send(:param_name).should == 'bar' end + it "should have pagination definition" do + prepare :total_pages => 1 + @renderer.pagination.should == [:previous_page, 1, :next_page] + end + describe "visible page numbers" do it "should calculate windowed visible links" do prepare({ :page => 6, :total_pages => 11 }, :inner_window => 1, :outer_window => 1) - showing_pages 1, 2, 5, 6, 7, 10, 11 + showing_pages 1, 2, :gap, 5, 6, 7, :gap, 10, 11 end it "should eliminate small gaps" do @@ -67,22 +68,22 @@ class LegacyCollection < WillPaginate::Collection it "should support having no windows at all" do prepare({ :page => 4, :total_pages => 7 }, :inner_window => 0, :outer_window => 0) - showing_pages 1, 4, 7 + showing_pages 1, :gap, 4, :gap, 7 end it "should adjust upper limit if lower is out of bounds" do prepare({ :page => 1, :total_pages => 10 }, :inner_window => 2, :outer_window => 1) - showing_pages 1, 2, 3, 4, 5, 9, 10 + showing_pages 1, 2, 3, 4, 5, :gap, 9, 10 end it "should adjust lower limit if upper is out of bounds" do prepare({ :page => 10, :total_pages => 10 }, :inner_window => 2, :outer_window => 1) - showing_pages 1, 2, 6, 7, 8, 9, 10 + showing_pages 1, 2, :gap, 6, 7, 8, 9, 10 end def showing_pages(*pages) pages = pages.first.to_a if Array === pages.first or Range === pages.first - @renderer.send(:visible_page_numbers).should == pages + @renderer.send(:windowed_page_numbers).should == pages end end From 7a8b83b22f77939adc2fd7a6abadd68a8ca0d1f0 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mislav=20Marohni=C4=87?= Date: Sun, 12 Oct 2008 05:08:27 +0200 Subject: [PATCH 056/168] BACKWARDS INCOMPATIBLE: revamp LinkRenderer, greatly reducing its dependency on ActionView and making it easier to modify by subclassing --- .../view_helpers/link_renderer.rb | 75 ++++++++++++------- spec/view_helpers/action_view_spec.rb | 8 +- 2 files changed, 52 insertions(+), 31 deletions(-) diff --git a/lib/will_paginate/view_helpers/link_renderer.rb b/lib/will_paginate/view_helpers/link_renderer.rb index 898807eb4..d02e1bab2 100644 --- a/lib/will_paginate/view_helpers/link_renderer.rb +++ b/lib/will_paginate/view_helpers/link_renderer.rb @@ -7,10 +7,6 @@ module ViewHelpers # links. It is used by +will_paginate+ helper internally. class LinkRenderer < LinkRendererBase - def initialize - @gap_marker = '' - end - # * +collection+ is a WillPaginate::Collection instance or any other object # that conforms to that API # * +options+ are forwarded from +will_paginate+ view helper @@ -18,21 +14,18 @@ def initialize def prepare(collection, options, template) super(collection, options) @template = template - # reset values in case we're re-using this instance - @url_string = nil end # Process it! This method returns the complete HTML string which contains # pagination links. Feel free to subclass LinkRenderer and change this # method as you see fit. def to_html - links = @options[:page_links] ? windowed_links : [] - # previous/next buttons - links.unshift page_link_or_span(@collection.previous_page, 'disabled prev_page', @options[:previous_label]) - links.push page_link_or_span(@collection.next_page, 'disabled next_page', @options[:next_label]) + links = pagination.map do |item| + item.is_a?(Fixnum) ? page_number(item) : send(item) + end html = links.join(@options[:separator]) - @options[:container] ? @template.content_tag(:div, html, html_attributes) : html + @options[:container] ? tag(:div, html, html_attributes) : html end # Returns the subset of +options+ this instance was initialized with that @@ -48,30 +41,58 @@ def html_attributes end protected - - def page_link_or_span(page, span_class, text = nil) - text ||= page.to_s - - if page and page != current_page - classnames = span_class && span_class.index(' ') && span_class.split(' ', 2).last - page_link page, text, :rel => rel_value(page), :class => classnames + + def page_number(page) + unless page == current_page + link page, page, :rel => rel_value(page) else - page_span page, text, :class => span_class + tag :span, page, :class => 'current' end end - - def page_link(page, text, attributes = {}) - @template.link_to text, url_for(page), attributes + + def gap + '' end - - def page_span(page, text, attributes = {}) - @template.content_tag :span, text, attributes + + def previous_page + previous_or_next_page(@collection.previous_page, @options[:previous_label], 'prev_page') + end + + def next_page + previous_or_next_page(@collection.next_page, @options[:next_label], 'next_page') + end + + def previous_or_next_page(page, text, classname) + if page + link text, page, :class => classname + else + tag :span, text, :class => classname + ' disabled' + end + end + + def link(text, target, attributes = {}) + if target.is_a? Fixnum + attributes[:rel] = rel_value(target) + target = url(target) + end + attributes[:href] = target + tag(:a, text, attributes) + end + + def tag(name, value, attributes = {}) + string_attributes = attributes.inject('') do |str, pair| + unless pair.last.nil? + str << %( #{pair.first}="#{CGI::escapeHTML(pair.last.to_s)}") + end + str + end + "<#{name}#{string_attributes}>#{value}" end # Returns URL params for +page_link_or_span+, taking the current GET params # and :params option into account. - def url_for(page) - url_params = { } + def url(page) + url_params = { :escape => false } # page links should preserve GET parameters stringified_merge url_params, @template.params if @template.request.get? stringified_merge url_params, @options[:params] if @options[:params] diff --git a/spec/view_helpers/action_view_spec.rb b/spec/view_helpers/action_view_spec.rb index e0a585e42..472ff11d4 100644 --- a/spec/view_helpers/action_view_spec.rb +++ b/spec/view_helpers/action_view_spec.rb @@ -76,7 +76,7 @@ def render(locals) it "should paginate using a custom renderer instance" do renderer = WillPaginate::ViewHelpers::LinkRenderer.new - renderer.gap_marker = '~~' + def renderer.gap() '~~' end paginate({ :per_page => 2 }, :inner_window => 0, :outer_window => 0, :renderer => renderer) do assert_select 'span.my-gap', '~~' @@ -106,7 +106,7 @@ def render(locals) it "should match expected markup" do paginate expected = <<-HTML -