zeke (owner)

Revisions

gist: 214750 Download_button fork
public
Public Clone URL: git://gist.github.com/214750.git
Embed All Files: show embed
ar_pagination_in_sinatra.rb #
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
module ActiveRecord
  class Base
    def self.paginate(opts = {})
      per_page = opts[:per_page] ||= 10
      page = (opts[:page].blank? ? 1 : opts[:page].to_i)
      total = self.count
      offset = (page - 1) * per_page
      collection = self.all(:order => "created_at DESC", :limit => per_page, :offset => offset)
      next_page = (total > (per_page * page) ? (page + 1) : nil)
      prev_page = (page > 1 ? (page - 1) : nil)
      total_pages = (total.to_f/per_page.to_f).ceil
      {:collection => collection, :next_page => next_page, :prev_page => prev_page, :page => page, :total_pages => total_pages}
    end
  end
end
 
helpers do
 
  def pagination_links(pagination_hash)
    links = []
    links << link("Previous", "/photos?page=#{pagination_hash[:prev_page]}") unless pagination_hash[:prev_page].nil?
    links << 1.upto(pagination_hash[:total_pages].to_i).map { |n| link(n, "/photos?page=#{n}") }
    links << link("Next", "/photos?page=#{pagination_hash[:next_page]}") unless pagination_hash[:next_page].nil?
    content_tag(:ul, convert_to_list_items(links.flatten), :class => "pagination")
  end
  
  # Give this helper an array, and get back a string of <li> elements.
  # The first item gets a class of first and the last, well.. last.
  # This makes it easier to apply CSS styles to lists, be they ordered or unordered.
  # http://zeke.tumblr.com/post/98025647/a-nice-little-view-helper-for-generating-list-items
  unless defined?(convert_to_list_items)
    def convert_to_list_items(items)
      items.inject([]) do |all, item|
        css = []
        css << "first" if items.first == item
        css << "last" if items.last == item
        all << content_tag(:li, item, :class => css.join(" "))
      end.join("\n")
    end
  end
  
  class Object
    unless method_defined? "blank?"
      # Snagged from Rails: http://api.rubyonrails.org/classes/Object.html#M000265
      def blank?
        respond_to?(:empty?) ? empty? : !self
      end
    end
  end
 
end