Report abuse

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
52
53
54
55
56
57
58
59
60
61
62
63
# your_sinatra_app.rb
require 'rubygems'
require 'bundler/setup'
Bundler.require :default
require 'your_model.rb'

class Application < Sinatra::Base
  get '/' do
    @articles = Article.order("created_at desc").
      paginate :page => params[:page], :per_page => 10
    haml :articles
  end

  # inspired from http://pastie.org/1192729 by krishnaprasad
  helpers do
    def to_params(params_hash)
      new_params = ''
      stack = []

      params_hash.each do |k, v|
        unless k == "page"
          if v.is_a?(Hash)
            stack << [k,v]
          else
            new_params << "#{k}=#{v}&"
          end
        end
      end

      stack.each do |parent, hash|
        hash.each do |k, v|
          unless k == "page"
            if v.is_a?(Hash)
              stack << ["#{parent}[#{k}]", v]
            else
              new_params << "#{parent}[#{k}]=#{v}&"
            end
          end
        end
      end

      new_params.chop! # trailing &
      "&" + new_params unless new_params.empty?
    end

    def paginate(resources)
      parameters = to_params(params.clone)

      if !resources.next_page.nil? and !resources.previous_page.nil?
        html = %^<a href="#{request.path_info}?page=#{resources.previous_page}#{parameters}">&laquo; Prev</a> ^
        html += "#{params[:page]} of #{resources.total_pages} "
        html += %^<a href="#{request.path_info}?page=#{resources.next_page}#{parameters}">Next &raquo;</a>^
      elsif !resources.next_page.nil? and resources.previous_page.nil?
        html = %^<a href="#{request.path_info}?page=#{resources.next_page}#{parameters}">Next &raquo;</a>^
      elsif resources.next_page.nil? and !resources.previous_page.nil?
        html = %^<a href="#{request.path_info}?page=#{resources.previous_page}#{parameters}">&laquo; Prev</a> ^
        html += "#{params[:page]} of #{resources.total_pages}"
      end

      html
    end
  end
end