From 3cdcb5ca02a94b2b342c30903a27d47d35d46e55 Mon Sep 17 00:00:00 2001 From: hukl Date: Tue, 17 Feb 2009 12:47:49 +0100 Subject: added will_paginate plugin --- vendor/plugins/will_paginate/lib/will_paginate.rb | 78 +++++ .../will_paginate/lib/will_paginate/array.rb | 16 + .../will_paginate/lib/will_paginate/collection.rb | 146 ++++++++ .../will_paginate/lib/will_paginate/core_ext.rb | 32 ++ .../will_paginate/lib/will_paginate/finder.rb | 264 ++++++++++++++ .../will_paginate/lib/will_paginate/named_scope.rb | 170 +++++++++ .../lib/will_paginate/named_scope_patch.rb | 37 ++ .../will_paginate/lib/will_paginate/version.rb | 9 + .../lib/will_paginate/view_helpers.rb | 389 +++++++++++++++++++++ 9 files changed, 1141 insertions(+) create mode 100644 vendor/plugins/will_paginate/lib/will_paginate.rb create mode 100644 vendor/plugins/will_paginate/lib/will_paginate/array.rb create mode 100644 vendor/plugins/will_paginate/lib/will_paginate/collection.rb create mode 100644 vendor/plugins/will_paginate/lib/will_paginate/core_ext.rb create mode 100644 vendor/plugins/will_paginate/lib/will_paginate/finder.rb create mode 100644 vendor/plugins/will_paginate/lib/will_paginate/named_scope.rb create mode 100644 vendor/plugins/will_paginate/lib/will_paginate/named_scope_patch.rb create mode 100644 vendor/plugins/will_paginate/lib/will_paginate/version.rb create mode 100644 vendor/plugins/will_paginate/lib/will_paginate/view_helpers.rb (limited to 'vendor/plugins/will_paginate/lib') diff --git a/vendor/plugins/will_paginate/lib/will_paginate.rb b/vendor/plugins/will_paginate/lib/will_paginate.rb new file mode 100644 index 0000000..e072412 --- /dev/null +++ b/vendor/plugins/will_paginate/lib/will_paginate.rb @@ -0,0 +1,78 @@ +require 'active_support' + +# = You *will* paginate! +# +# First read about WillPaginate::Finder::ClassMethods, then see +# WillPaginate::ViewHelpers. The magical array you're handling in-between is +# WillPaginate::Collection. +# +# Happy paginating! +module WillPaginate + class << self + # shortcut for enable_actionpack and enable_activerecord combined + def enable + enable_actionpack + enable_activerecord + end + + # hooks WillPaginate::ViewHelpers into ActionView::Base + def enable_actionpack + return if ActionView::Base.instance_methods.include? 'will_paginate' + require 'will_paginate/view_helpers' + ActionView::Base.send :include, ViewHelpers + + if defined?(ActionController::Base) and ActionController::Base.respond_to? :rescue_responses + ActionController::Base.rescue_responses['WillPaginate::InvalidPage'] = :not_found + end + end + + # hooks WillPaginate::Finder into ActiveRecord::Base and classes that deal + # with associations + def enable_activerecord + return if ActiveRecord::Base.respond_to? :paginate + require 'will_paginate/finder' + ActiveRecord::Base.send :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.send :include, Finder::ClassMethods + klass.class_eval { alias_method_chain :method_missing, :paginate } + 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). + # + # 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 + + ActiveRecord::Base.send :include, WillPaginate::NamedScope + end + end + + module Deprecation # :nodoc: + extend ActiveSupport::Deprecation + + def self.warn(message, callstack = caller) + message = 'WillPaginate: ' + message.strip.gsub(/\s+/, ' ') + ActiveSupport::Deprecation.warn(message, callstack) + end + end +end + +if defined?(Rails) and defined?(ActiveRecord) and defined?(ActionController) + WillPaginate.enable +end diff --git a/vendor/plugins/will_paginate/lib/will_paginate/array.rb b/vendor/plugins/will_paginate/lib/will_paginate/array.rb new file mode 100644 index 0000000..d061d2b --- /dev/null +++ b/vendor/plugins/will_paginate/lib/will_paginate/array.rb @@ -0,0 +1,16 @@ +require 'will_paginate/collection' + +# http://www.desimcadam.com/archives/8 +Array.class_eval do + 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| + pager.replace self[pager.offset, pager.per_page].to_a + } + end +end diff --git a/vendor/plugins/will_paginate/lib/will_paginate/collection.rb b/vendor/plugins/will_paginate/lib/will_paginate/collection.rb new file mode 100644 index 0000000..e253570 --- /dev/null +++ b/vendor/plugins/will_paginate/lib/will_paginate/collection.rb @@ -0,0 +1,146 @@ +module WillPaginate + # = Invalid page number error + # This is an ArgumentError raised in case a page was requested that is either + # zero or negative number. You should decide how do deal with such errors in + # the controller. + # + # If you're using Rails 2, then this error will automatically get handled like + # 404 Not Found. The hook is in "will_paginate.rb": + # + # ActionController::Base.rescue_responses['WillPaginate::InvalidPage'] = :not_found + # + # If you don't like this, use your preffered method of rescuing exceptions in + # public from your controllers to handle this differently. The +rescue_from+ + # method is a nice addition to Rails 2. + # + # This error is *not* raised when a page further than the last page is + # requested. Use WillPaginate::Collection#out_of_bounds? method to + # check for those cases and manually deal with them as you see fit. + class InvalidPage < ArgumentError + def initialize(page, page_num) + super "#{page.inspect} given as value, which translates to '#{page_num}' as page number" + end + end + + # = The key to pagination + # Arrays returned from paginating finds are, in fact, instances of this little + # class. You may think of WillPaginate::Collection as an ordinary array with + # some extra properties. Those properties are used by view helpers to generate + # correct page links. + # + # WillPaginate::Collection also assists in rolling out your own pagination + # solutions: see +create+. + # + # If you are writing a library that provides a collection which you would like + # to conform to this API, you don't have to copy these methods over; simply + # make your plugin/gem dependant on the "mislav-will_paginate" gem: + # + # gem 'mislav-will_paginate' + # require 'will_paginate/collection' + # + # # WillPaginate::Collection is now available for use + class Collection < Array + attr_reader :current_page, :per_page, :total_entries, :total_pages + + # Arguments to the constructor are the current page number, per-page limit + # and the total number of entries. The last argument is optional because it + # is best to do lazy counting; in other words, count *conditionally* after + # populating the collection using the +replace+ method. + def initialize(page, per_page, total = nil) + @current_page = page.to_i + raise InvalidPage.new(page, @current_page) if @current_page < 1 + @per_page = per_page.to_i + raise ArgumentError, "`per_page` setting cannot be less than 1 (#{@per_page} given)" if @per_page < 1 + + self.total_entries = total if total + end + + # Just like +new+, but yields the object after instantiation and returns it + # afterwards. This is very useful for manual pagination: + # + # @entries = WillPaginate::Collection.create(1, 10) do |pager| + # result = Post.find(:all, :limit => pager.per_page, :offset => pager.offset) + # # inject the result array into the paginated collection: + # pager.replace(result) + # + # unless pager.total_entries + # # the pager didn't manage to guess the total count, do it manually + # pager.total_entries = Post.count + # end + # end + # + # The possibilities with this are endless. For another example, here is how + # WillPaginate used to define pagination for Array instances: + # + # Array.class_eval do + # def paginate(page = 1, per_page = 15) + # WillPaginate::Collection.create(page, per_page, size) do |pager| + # pager.replace self[pager.offset, pager.per_page].to_a + # end + # end + # end + # + # The Array#paginate API has since then changed, but this still serves as a + # fine example of WillPaginate::Collection usage. + def self.create(page, per_page, total = nil) + pager = new(page, per_page, total) + yield pager + pager + end + + # Helper method that is true when someone tries to fetch a page with a + # larger number than the last page. Can be used in combination with flashes + # and redirecting. + def out_of_bounds? + current_page > total_pages + end + + # Current offset of the paginated collection. If we're on the first page, + # it is always 0. If we're on the 2nd page and there are 30 entries per page, + # the offset is 30. This property is useful if you want to render ordinals + # side by side with records in the view: simply start with offset + 1. + def offset + (current_page - 1) * per_page + end + + # current_page - 1 or nil if there is no previous page + def previous_page + current_page > 1 ? (current_page - 1) : nil + end + + # current_page + 1 or nil if there is no next page + def next_page + current_page < total_pages ? (current_page + 1) : nil + end + + # sets the total_entries property and calculates total_pages + def total_entries=(number) + @total_entries = number.to_i + @total_pages = (@total_entries / per_page.to_f).ceil + end + + # This is a magic wrapper for the original Array#replace method. It serves + # for populating the paginated collection after initialization. + # + # Why magic? Because it tries to guess the total number of entries judging + # by the size of given array. If it is shorter than +per_page+ limit, then we + # know we're on the last page. This trick is very useful for avoiding + # unnecessary hits to the database to do the counting after we fetched the + # data for the current page. + # + # However, after using +replace+ you should always test the value of + # +total_entries+ and set it to a proper value if it's +nil+. See the example + # in +create+. + def replace(array) + result = super + + # The collection is shorter then page limit? Rejoice, because + # then we know that we are on the last page! + if total_entries.nil? and length < per_page and (current_page == 1 or length > 0) + self.total_entries = offset + length + end + + result + end + end +end diff --git a/vendor/plugins/will_paginate/lib/will_paginate/core_ext.rb b/vendor/plugins/will_paginate/lib/will_paginate/core_ext.rb new file mode 100644 index 0000000..32f10f5 --- /dev/null +++ b/vendor/plugins/will_paginate/lib/will_paginate/core_ext.rb @@ -0,0 +1,32 @@ +require 'set' +require 'will_paginate/array' + +unless Hash.instance_methods.include? 'except' + Hash.class_eval do + # Returns a new hash without the given keys. + def except(*keys) + rejected = Set.new(respond_to?(:convert_key) ? keys.map { |key| convert_key(key) } : keys) + reject { |key,| rejected.include?(key) } + end + + # Replaces the hash without only the given keys. + def except!(*keys) + replace(except(*keys)) + end + end +end + +unless Hash.instance_methods.include? 'slice' + Hash.class_eval do + # Returns a new hash with only the given keys. + def slice(*keys) + allowed = Set.new(respond_to?(:convert_key) ? keys.map { |key| convert_key(key) } : keys) + reject { |key,| !allowed.include?(key) } + end + + # Replaces the hash with only the given keys. + def slice!(*keys) + replace(slice(*keys)) + end + end +end diff --git a/vendor/plugins/will_paginate/lib/will_paginate/finder.rb b/vendor/plugins/will_paginate/lib/will_paginate/finder.rb new file mode 100644 index 0000000..d0e5668 --- /dev/null +++ b/vendor/plugins/will_paginate/lib/will_paginate/finder.rb @@ -0,0 +1,264 @@ +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) + 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) { |*a| yield(*a) if block_given? }) + + # 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 {Faking Cursors in ActiveRecord}[http://weblog.jamisbuck.org/2007/4/6/faking-cursors-in-activerecord] + # where Jamis Buck describes this and a more efficient way for MySQL. + def paginated_each(options = {}) + 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) + with_exclusive_scope(:find => {}) do + # using exclusive scope so that the block is yielded in scope-free context + total += collection.each { |item| yield item }.size + end + 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.dup) + 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) #:nodoc: + # did somebody tried to paginate? if not, let them be + unless method.to_s.index('paginate') == 0 + if block_given? + return method_missing_without_paginate(method, *args) { |*a| yield(*a) } + else + return method_missing_without_paginate(method, *args) + end + 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) { |*a| yield(*a) if block_given? } + 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] + excludees << :from unless ActiveRecord::Calculations::CALCULATIONS_OPTIONS.include?(:from) + + # we may be in a model or an association proxy + klass = (@owner and @reflection) ? @reflection.klass : self + + # 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 # 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] + + # 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 + + # we may have to scope ... + counter = Proc.new { count(count_options) } + + 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 finder =~ /^find_(all_by|by)_([_a-zA-Z]\w*)$/ + # extract conditions from calls like "paginate_by_foo_and_bar" + attribute_names = $2.split('_and_') + 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 + end +end diff --git a/vendor/plugins/will_paginate/lib/will_paginate/named_scope.rb b/vendor/plugins/will_paginate/lib/will_paginate/named_scope.rb new file mode 100644 index 0000000..5a743d7 --- /dev/null +++ b/vendor/plugins/will_paginate/lib/will_paginate/named_scope.rb @@ -0,0 +1,170 @@ +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) + # + # 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 :scoped, lambda { |scope| scope } + end + end + + module ClassMethods + def scopes + read_inheritable_attribute(:scopes) || write_inheritable_attribute(:scopes, {}) + end + + # Adds a class method for retrieving and querying objects. A scope represents a narrowing of a database query, + # such as :conditions => {:color => :red}, :select => 'shirts.*', :include => :washing_instructions. + # + # class Shirt < ActiveRecord::Base + # named_scope :red, :conditions => {:color => 'red'} + # named_scope :dry_clean_only, :joins => :washing_instructions, :conditions => ['washing_instructions.dry_clean_only = ?', true] + # end + # + # The above calls to named_scope define class methods Shirt.red and Shirt.dry_clean_only. Shirt.red, + # in effect, represents the query Shirt.find(:all, :conditions => {:color => 'red'}). + # + # Unlike Shirt.find(...), however, the object returned by Shirt.red is not an Array; it resembles the association object + # constructed by a has_many declaration. For instance, you can invoke Shirt.red.find(:first), Shirt.red.count, + # Shirt.red.find(:all, :conditions => {:size => 'small'}). Also, just + # as with the association objects, name scopes acts like an Array, implementing Enumerable; Shirt.red.each(&block), + # Shirt.red.first, and Shirt.red.inject(memo, &block) all behave as if Shirt.red really were an Array. + # + # These named scopes are composable. For instance, Shirt.red.dry_clean_only will produce all shirts that are both red and dry clean only. + # 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::Base descendent upon which the scopes were defined. But they are also available to + # has_many associations. If, + # + # class Person < ActiveRecord::Base + # has_many :shirts + # end + # + # then elton.shirts.red.dry_clean_only will return all of Elton's red, dry clean + # only shirts. + # + # Named scopes can also be procedural. + # + # class Shirt < ActiveRecord::Base + # named_scope :colored, lambda { |color| + # { :conditions => { :color => color } } + # } + # end + # + # In this example, Shirt.colored('puce') finds all puce shirts. + # + # Named scopes can also have extensions, just as with has_many declarations: + # + # class Shirt < ActiveRecord::Base + # named_scope :red, :conditions => {:color => 'red'} do + # def dom_id + # 'red_shirts' + # end + # 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 = {}) + name = name.to_sym + scopes[name] = lambda do |parent_scope, *args| + Scope.new(parent_scope, case options + when Hash + options + when Proc + options.call(*args) + end) { |*a| yield(*a) if block_given? } + end + (class << self; self end).instance_eval do + define_method name do |*args| + scopes[name].call(self, *args) + end + end + end + end + + class Scope + attr_reader :proxy_scope, :proxy_options + + [].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) + [options[:extend]].flatten.each { |extension| extend extension } if options[:extend] + extend Module.new { |*args| yield(*args) } if block_given? + @proxy_scope, @proxy_options = proxy_scope, options.except(:extend) + end + + 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 + end + + private + def method_missing(method, *args) + if scopes.include?(method) + scopes[method].call(self, *args) + else + with_scope :find => proxy_options do + proxy_scope.send(method, *args) { |*a| yield(*a) if block_given? } + end + end + end + + def load_found + @found = find(:all) + end + end + end +end diff --git a/vendor/plugins/will_paginate/lib/will_paginate/named_scope_patch.rb b/vendor/plugins/will_paginate/lib/will_paginate/named_scope_patch.rb new file mode 100644 index 0000000..7daff59 --- /dev/null +++ b/vendor/plugins/will_paginate/lib/will_paginate/named_scope_patch.rb @@ -0,0 +1,37 @@ +ActiveRecord::Associations::AssociationProxy.class_eval do + protected + def with_scope(*args) + @reflection.klass.send(:with_scope, *args) { |*a| yield(*a) if block_given? } + end +end + +[ ActiveRecord::Associations::AssociationCollection, + ActiveRecord::Associations::HasManyThroughAssociation ].each do |klass| + klass.class_eval do + protected + alias :method_missing_without_scopes :method_missing_without_paginate + def method_missing_without_paginate(method, *args) + if @reflection.klass.scopes.include?(method) + @reflection.klass.scopes[method].call(self, *args) { |*a| yield(*a) if block_given? } + else + method_missing_without_scopes(method, *args) { |*a| yield(*a) if block_given? } + end + end + end +end + +# Rails 1.2.6 +ActiveRecord::Associations::HasAndBelongsToManyAssociation.class_eval do + protected + def method_missing(method, *args) + if @target.respond_to?(method) || (!@reflection.klass.respond_to?(method) && Class.respond_to?(method)) + super + elsif @reflection.klass.scopes.include?(method) + @reflection.klass.scopes[method].call(self, *args) + else + @reflection.klass.with_scope(:find => { :conditions => @finder_sql, :joins => @join_sql, :readonly => false }) do + @reflection.klass.send(method, *args) { |*a| yield(*a) if block_given? } + end + end + end +end if ActiveRecord::Base.respond_to? :find_first diff --git a/vendor/plugins/will_paginate/lib/will_paginate/version.rb b/vendor/plugins/will_paginate/lib/will_paginate/version.rb new file mode 100644 index 0000000..99f3238 --- /dev/null +++ b/vendor/plugins/will_paginate/lib/will_paginate/version.rb @@ -0,0 +1,9 @@ +module WillPaginate + module VERSION + MAJOR = 2 + MINOR = 3 + TINY = 5 + + STRING = [MAJOR, MINOR, TINY].join('.') + end +end diff --git a/vendor/plugins/will_paginate/lib/will_paginate/view_helpers.rb b/vendor/plugins/will_paginate/lib/will_paginate/view_helpers.rb new file mode 100644 index 0000000..5f7ae42 --- /dev/null +++ b/vendor/plugins/will_paginate/lib/will_paginate/view_helpers.rb @@ -0,0 +1,389 @@ +require 'will_paginate/core_ext' + +module WillPaginate + # = Will Paginate view helpers + # + # The main view helper, #will_paginate, renders + # pagination links for the given collection. The helper itself is lightweight + # and serves only as a wrapper around LinkRenderer instantiation; the + # renderer then does all the hard work of generating the HTML. + # + # == Global options for helpers + # + # Options for pagination helpers are optional and get their default values from the + # WillPaginate::ViewHelpers.pagination_options hash. You can write to this hash to + # override default options on the global level: + # + # WillPaginate::ViewHelpers.pagination_options[:previous_label] = 'Previous page' + # + # By putting this into "config/initializers/will_paginate.rb" (or simply environment.rb in + # older versions of Rails) you can easily translate link texts to previous + # and next pages, as well as override some other defaults to your liking. + module ViewHelpers + # default options that can be overridden on the global level + @@pagination_options = { + :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::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 + # Display options: + # * :previous_label -- default: "« Previous" (this parameter is called :prev_label in versions 2.3.2 and older!) + # * :next_label -- default: "Next »" + # * :page_links -- when false, only previous/next links are rendered (default: true) + # * :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) + # + # HTML options: + # * :class -- CSS class name for the generated DIV (default: "pagination") + # * :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". + # + # Advanced options: + # * :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) + # + # All options not recognized by will_paginate will become HTML attributes on the container + # element for pagination links (the DIV). For example: + # + # <%= will_paginate @posts, :style => 'font-size: small' %> + # + # ... 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 + if options[:prev_label] + WillPaginate::Deprecation::warn(":prev_label view parameter is now :previous_label; the old name has been deprecated", caller) + options[:previous_label] = options.delete(:prev_label) + end + + # 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 + + unless ActionView::Base.respond_to? :erb_variable + concat pagination + yield + concat pagination + else + content = pagination + capture(&block) + pagination + concat(content, block.binding) + end + 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 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') + WillPaginate::Deprecation.warn %{ + You are using a paginated collection of class #{collection.class.name} + which conforms to the old API of WillPaginate::Collection by using + `page_count`, while the current method name is `total_pages`. Please + upgrade yours or 3rd-party code that provides the paginated collection}, caller + class << collection + def total_pages; page_count; end + end + end + collection.total_pages + end + end + + # This class does the heavy lifting of actually building the pagination + # links. It is used by the 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[:previous_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 = {} + # 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 + + # Recursively merge into target hash by using stringified keys from the other one + def stringified_merge(target, other) + other.each do |key, value| + key = key.to_s # this line is what it's all about! + existing = target[key] + + if value.is_a?(Hash) and (existing.is_a?(Hash) or existing.nil?) + stringified_merge(existing || (target[key] = {}), value) + else + target[key] = value + end + end + end + end +end -- cgit v1.3