Created
February 11, 2012 21:42
-
-
Save gotmayonase/1804434 to your computer and use it in GitHub Desktop.
A link renderer for WillPaginate that converts your pagination to a hash for rendering in Json
This file contains hidden or 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
object false | |
child @products => 'products' do | |
attributes :name, :description, :id | |
end | |
node(:pagination) { will_paginate(@products, :renderer => JsonRenderer) } |
This file contains hidden or 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
class JsonRenderer < WillPaginate::ViewHelpers::LinkRendererBase | |
def prepare(collection, options, context) | |
super(collection, options) | |
@context = context | |
end | |
def to_json | |
{ | |
:next_page => url(next_page), | |
:previous_page => url(previous_page) | |
} | |
end | |
alias :to_html :to_json | |
private | |
def url(page) | |
return nil unless page | |
@context.url_for(:page => page, :per_page => @collection.per_page) | |
end | |
def previous_page | |
@collection.current_page > 1 && @collection.current_page - 1 | |
end | |
def next_page | |
@collection.current_page < @collection.total_pages && @collection.current_page + 1 | |
end | |
end | |
class Hash | |
def html_safe | |
self | |
end | |
end |
This file contains hidden or 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
class ProductsController < ApplicationController | |
include WillPaginate::ViewHelpers | |
def index | |
@products = Product.paginate(:page => params[:page], :per_page => params[:per_page]) | |
render :json => { :products => @products, :pagination => will_paginate(@products, :renderer => JsonRenderer) } | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment