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
- #page ⇒ Object
- #paginate(resource, options = {}) ⇒ Object
- #paginate_haml ⇒ Object
- #paginate_options(resource, options) ⇒ Object
- #pagination_url(*path) ⇒ Object
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
#page ⇒ Object
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
9 10 11 12 13 14 15 16 17 |
# File 'lib/sinatra/paginate.rb', line 9 def paginate resource, = {} raise ArgumentError, 'resource should respond to :total' unless resource.respond_to?(:total) raise ArgumentError, 'resource should respond to :size' unless resource.respond_to?(:size) = DEFAULTS.merge() view = .fetch(:view, paginate_haml) renderer = .fetch(:renderer) send(renderer, view, layout: false, locals: (resource, )) end |
#paginate_haml ⇒ Object
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 resource, last = (resource.total / [:items_per_page].to_f).ceil page = [1, params['page'].to_i].max from = [1, page - ([:width] >> 1)].max to = [from + [:width] - 1, last].min while (to - from + 1) < [: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: .fetch(:uri, request.path_info), labels: .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 |