Initial commit of foodsoft 2

This commit is contained in:
Benjamin Meichsner 2009-01-06 11:49:19 +01:00
commit 5b9a7e05df
657 changed files with 70444 additions and 0 deletions

View file

@ -0,0 +1,82 @@
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 <tt>enable_actionpack</tt> and <tt>enable_activerecord</tt> 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 <tt>named_scope</tt> broke
# has_many, has_many :through or has_and_belongs_to_many associations in
# your app. By passing +false+, you can still use <tt>named_scope</tt> 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+/, ' ')
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)
WillPaginate.enable
end

View file

@ -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

View file

@ -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 <tt>WillPaginate::Collection#out_of_bounds?</tt> 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, &block)
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 <tt>total_entries</tt> property and calculates <tt>total_pages</tt>
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

View file

@ -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

View file

@ -0,0 +1,247 @@
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 <tt>:page</tt> 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 <tt>:all</tt> 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 <tt>:order</tt> parameter
#
# In ActiveRecord finders, <tt>:order</tt> parameter specifies columns for
# the <tt>ORDER BY</tt> clause in SQL. It is important to have it, since
# pagination only makes sense with ordered sets. Without the <tt>ORDER
# BY</tt> clause, databases aren't required to do consistent ordering when
# performing <tt>SELECT</tt> 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
# * <tt>:page</tt> -- REQUIRED, but defaults to 1 if false or nil
# * <tt>:per_page</tt> -- defaults to <tt>CurrentModel.per_page</tt> (which is 30 if not overridden)
# * <tt>:total_entries</tt> -- use only if you manually count total entries
# * <tt>:count</tt> -- additional options that are passed on to +count+
# * <tt>:finder</tt> -- 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 <tt>:page</tt> (default is 1). Default
# <tt>:order</tt> is <tt>"id"</tt>, 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 = {}, &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 <tt>:total_entries</tt>. 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 be in a model or an association proxy
klass = (@owner and @reflection) ? @reflection.klass : self
# 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 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
end
end

View file

@ -0,0 +1,132 @@
## 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:
# * <tt>all</tt>, which is similar to a <tt>find(:all)</tt> query, and
# * <tt>scoped</tt>, 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:
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 <tt>:conditions => {:color => :red}, :select => 'shirts.*', :include => :washing_instructions</tt>.
#
# 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 <tt>named_scope</tt> define class methods <tt>Shirt.red</tt> and <tt>Shirt.dry_clean_only</tt>. <tt>Shirt.red</tt>,
# in effect, represents the query <tt>Shirt.find(:all, :conditions => {:color => 'red'})</tt>.
#
# Unlike Shirt.find(...), however, the object returned by <tt>Shirt.red</tt> is not an Array; it resembles the association object
# constructed by a <tt>has_many</tt> declaration. For instance, you can invoke <tt>Shirt.red.find(:first)</tt>, <tt>Shirt.red.count</tt>,
# <tt>Shirt.red.find(:all, :conditions => {:size => 'small'})</tt>. Also, just
# as with the association objects, name scopes acts like an Array, implementing Enumerable; <tt>Shirt.red.each(&block)</tt>,
# <tt>Shirt.red.first</tt>, and <tt>Shirt.red.inject(memo, &block)</tt> all behave as if Shirt.red really were an Array.
#
# These named scopes are composable. For instance, <tt>Shirt.red.dry_clean_only</tt> will produce all shirts that are both red and dry clean only.
# Nested finds and calculations also work with these compositions: <tt>Shirt.red.dry_clean_only.count</tt> returns the number of garments
# for which these criteria obtain. Similarly with <tt>Shirt.red.dry_clean_only.average(:thread_count)</tt>.
#
# All scopes are available as class methods on the ActiveRecord descendent upon which the scopes were defined. But they are also available to
# <tt>has_many</tt> associations. If,
#
# class Person < ActiveRecord::Base
# has_many :shirts
# end
#
# then <tt>elton.shirts.red.dry_clean_only</tt> 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, <tt>Shirt.colored('puce')</tt> finds all puce shirts.
#
# Named scopes can also have extensions, just as with <tt>has_many</tt> declarations:
#
# class Shirt < ActiveRecord::Base
# named_scope :red, :conditions => {:color => 'red'} do
# def dom_id
# 'red_shirts'
# end
# end
# end
#
def named_scope(name, options = {}, &block)
scopes[name] = lambda do |parent_scope, *args|
Scope.new(parent_scope, case options
when Hash
options
when Proc
options.call(*args)
end, &block)
end
(class << self; self end).instance_eval do
define_method name do |*args|
scopes[name].call(self, *args)
end
end
end
end
class Scope #:nodoc:
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)/ }
delegate :scopes, :with_scope, :to => :proxy_scope
def initialize(proxy_scope, options, &block)
[options[:extend]].flatten.each { |extension| extend extension } if options[:extend]
extend Module.new(&block) if block_given?
@proxy_scope, @proxy_options = proxy_scope, options.except(:extend)
end
def reload
load_found; self
end
protected
def proxy_found
@found || load_found
end
private
def method_missing(method, *args, &block)
if scopes.include?(method)
scopes[method].call(self, *args)
else
with_scope :find => proxy_options do
proxy_scope.send(method, *args, &block)
end
end
end
def load_found
@found = find(:all)
end
end
end
end

View file

@ -0,0 +1,39 @@
## based on http://dev.rubyonrails.org/changeset/9084
ActiveRecord::Associations::AssociationProxy.class_eval do
protected
def with_scope(*args, &block)
@reflection.klass.send :with_scope, *args, &block
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, &block)
if @reflection.klass.scopes.include?(method)
@reflection.klass.scopes[method].call(self, *args, &block)
else
method_missing_without_scopes(method, *args, &block)
end
end
end
end
# Rails 1.2.6
ActiveRecord::Associations::HasAndBelongsToManyAssociation.class_eval do
protected
def method_missing(method, *args, &block)
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, &block)
end
end
end
end if ActiveRecord::Base.respond_to? :find_first

View file

@ -0,0 +1,9 @@
module WillPaginate
module VERSION
MAJOR = 2
MINOR = 3
TINY = 3
STRING = [MAJOR, MINOR, TINY].join('.')
end
end

View file

@ -0,0 +1,390 @@
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
# <tt>WillPaginate::ViewHelpers.pagination_options</tt> 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 => '&laquo; Previous',
:next_label => 'Next &raquo;',
: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,
# bennis hack for ajax-support
:remote => false
}
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:
# * <tt>:previous_label</tt> -- default: "« Previous"
# * <tt>:next_label</tt> -- default: "Next »"
# * <tt>:page_links</tt> -- when false, only previous/next links are rendered (default: true)
# * <tt>:inner_window</tt> -- how many links are shown around the current page (default: 4)
# * <tt>:outer_window</tt> -- how many links are around the first and the last page (default: 1)
# * <tt>:separator</tt> -- string separator for page HTML elements (default: single space)
#
# HTML options:
# * <tt>:class</tt> -- CSS class name for the generated DIV (default: "pagination")
# * <tt>:container</tt> -- toggles rendering of the DIV container for pagination links, set to
# false only when you are rendering your own pagination markup (default: true)
# * <tt>:id</tt> -- 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:
# * <tt>:param_name</tt> -- parameter name for page number in URLs (default: <tt>:page</tt>)
# * <tt>:params</tt> -- additional parameters when generating pagination links
# (eg. <tt>:controller => "foo", :action => nil</tt>)
# * <tt>:renderer</tt> -- class name, class or instance of a link renderer (default:
# <tt>WillPaginate::LinkRenderer</tt>)
#
# 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:
#
# <div class="pagination" style="font-size: small"> ... </div>
#
# ==== 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 <tt>@posts</tt>
# variable. Example:
#
# <%= will_paginate :id => true %>
#
# ... will result in <tt>@post</tt> collection getting paginated:
#
# <div class="pagination" id="posts_pagination"> ... </div>
#
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.")
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 %>
# <ol id="posts">
# <% for post in @posts %>
# <li> ... </li>
# <% end %>
# </ol>
# <% end %>
#
# will result in:
#
# <div class="pagination"> ... </div>
# <ol id="posts">
# ...
# </ol>
# <div class="pagination"> ... </div>
#
# Arguments are passed to a <tt>will_paginate</tt> call, so the same options
# apply. Don't use the <tt>:id</tt> 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 with the <tt>:entry_name</tt> 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 <b>1</b> #{entry_name}"
else; "Displaying <b>all #{collection.size}</b> #{entry_name.pluralize}"
end
else
%{Displaying #{entry_name.pluralize} <b>%d&nbsp;-&nbsp;%d</b> of <b>%d</b> 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 <<-MSG
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.
MSG
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 <tt>will_paginate</tt> helper internally.
class LinkRenderer
# The gap in page links is represented by:
#
# <span class="gap">&hellip;</span>
attr_accessor :gap_marker
def initialize
@gap_marker = '<span class="gap">&hellip;</span>'
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 <tt>:inner_window</tt> and
# <tt>:outer_window</tt> 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 = {})
# bennis hack to support ajax-support
if @options[:remote] == true
@template.link_to_remote text, :url => url_for(page), :html => attributes, :before => "Element.show('loader')", :success => "Element.hide('loader')"
else
@template.link_to text, url_for(page), attributes
end
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 <tt>:params</tt> 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!((?:\?|&amp;)#{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