Last active
September 7, 2016 18:39
-
-
Save dignoe/0f76e81949b46e48e4ff4f992aa93aeb to your computer and use it in GitHub Desktop.
Add rel="next" & rel="prev" to will_paginate gem (with custom paths)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# config/initializers/will_paginate_helper.rb | |
# Tested with will_paginate v3.0.7 | |
module WillPaginate | |
module ActionView | |
class LinkRenderer < ViewHelpers::LinkRenderer | |
include ListingHelper | |
protected | |
def url(page) | |
@base_url_params ||= begin | |
url_params = merge_get_params(default_url_params) | |
url_params[:only_path] = true | |
merge_optional_params(url_params) | |
end | |
url_params = @base_url_params.dup | |
add_current_page_param(url_params, page) | |
@options[:listings] ? url_for_listing(url_params) : @template.url_for(url_params) | |
end | |
def url_for_listing(url_params) | |
# custom listing path generator | |
listing_path(options, url_params) | |
end | |
end | |
def pagination_link_tags(collection = nil, options = {}) #:nodoc: | |
options, collection = collection, nil if collection.is_a? Hash | |
collection ||= infer_collection_from_controller | |
options = options.symbolize_keys | |
options[:renderer] ||= LinkRenderer | |
super(collection, options) | |
end | |
end | |
# Monkey patch for rel prev & next head tags needed for SEO | |
# https://github.com/mislav/will_paginate/pull/324 | |
# https://webmasters.googleblog.com/2011/09/pagination-with-relnext-and-relprev.html | |
module ViewHelpers | |
class LinkRenderer < LinkRendererBase | |
def to_link_tags | |
output = [] | |
link = '<link rel="%s" href="%s" />' | |
output << link % ["prev", url(@collection.previous_page)] if @collection.previous_page | |
output << link % ["next", url(@collection.next_page)] if @collection.next_page | |
output.join("\n") | |
end | |
end | |
def pagination_link_tags(collection, options = {}) | |
# early exit if there is nothing to render | |
return nil unless collection.total_pages > 1 | |
options = WillPaginate::ViewHelpers.pagination_options.merge(options) | |
# get the renderer instance | |
renderer = case options[:renderer] | |
when nil | |
raise ArgumentError, ":renderer not specified" | |
when String | |
klass = if options[:renderer].respond_to? :constantize then options[:renderer].constantize | |
else Object.const_get(options[:renderer]) # poor man's constantize | |
end | |
klass.new | |
when Class then options[:renderer].new | |
else options[:renderer] | |
end | |
# render HTML for pagination | |
renderer.prepare collection, options, self | |
output = renderer.to_link_tags | |
output = output.html_safe if output.respond_to?(:html_safe) | |
output | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment