Skip to content

Instantly share code, notes, and snippets.

@gotmayonase
Created February 11, 2012 21:42
Show Gist options
  • Save gotmayonase/1804434 to your computer and use it in GitHub Desktop.
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
object false
child @products => 'products' do
attributes :name, :description, :id
end
node(:pagination) { will_paginate(@products, :renderer => JsonRenderer) }
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
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