Module: Sinatra::Paginate

Defined in:
lib/sinatra/paginate.rb

Constant Summary collapse

DEFAULTS =
{items_per_page: 10, width: 5, renderer: 'haml', labels: {first: '«', last: '»'}}

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.registered(app) ⇒ Object



47
48
49
# File 'lib/sinatra/paginate.rb', line 47

def self.registered app
  app.helpers self
end

Instance Method Details

#pageObject



36
37
38
39
# File 'lib/sinatra/paginate.rb', line 36

def page
  page = params['page'].to_i
  page > 0 ? page : 1
end

#paginate(resource, options = {}) ⇒ Object

Raises:

  • (ArgumentError)


9
10
11
12
13
14
15
16
17
# File 'lib/sinatra/paginate.rb', line 9

def paginate resource, options = {}
  raise ArgumentError, 'resource should respond to :total' unless resource.respond_to?(:total)
  raise ArgumentError, 'resource should respond to :size'  unless resource.respond_to?(:size)

  options  = DEFAULTS.merge(options)
  view     = options.fetch(:view, paginate_haml)
  renderer = options.fetch(:renderer)
  send(renderer, view, layout: false, locals: paginate_options(resource, options))
end

#paginate_hamlObject



32
33
34
# File 'lib/sinatra/paginate.rb', line 32

def paginate_haml
  @@haml ||= File.read(__FILE__).sub %r{^.*__END__}m, ''
end

#paginate_options(resource, options) ⇒ Object



19
20
21
22
23
24
25
26
27
28
29
30
# File 'lib/sinatra/paginate.rb', line 19

def paginate_options resource, options
  last = (resource.total / options[:items_per_page].to_f).ceil
  page = [1, params['page'].to_i].max
  from = [1, page - (options[:width] >> 1)].max
  to   = [from + options[:width] - 1, last].min

  while (to - from + 1) < options[:width] && (to < last || from > 1)
    to   += 1 if to   < last
    from -= 1 if from > 1
  end
  {page: page, from: from, to: to, last: last, uri: options.fetch(:uri, request.path_info), labels: options.fetch(:labels)}
end

#pagination_url(*path) ⇒ Object



41
42
43
44
45
# File 'lib/sinatra/paginate.rb', line 41

def pagination_url *path
  params = path[-1].respond_to?(:to_hash) ? path.delete_at(-1).to_hash : {}
  params = params.empty? ? '' : '?' + URI.escape(params.map{|*a| a.join('=')}.join('&')).to_s
  ['/', path.compact.map(&:to_s)].flatten.join('/').gsub(%r{/+}, '/') + params
end