# hx/listing/paginate - Listing paginator # # Copyright (c) 2009-2010 MenTaLguY # # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and associated documentation files (the # "Software"), to deal in the Software without restriction, including # without limitation the rights to use, copy, modify, merge, publish, # distribute, sublicense, and/or sell copies of the Software, and to # permit persons to whom the Software is furnished to do so, subject to # the following conditions: # # The above copyright notice and this permission notice shall be # included in all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, # EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF # MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND # NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE # LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION # OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION # WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. require 'rubygems' require 'hx' module Hx module Listing class Paginate include Hx::Source def initialize(source, options) @source = source @page_size = options[:page_size] end def each_entry @source.each_entry do |index_path, index_entry| items = index_entry['items'] || [] if items.empty? index_entry = index_entry.dup index_entry['pages'] = [index_entry] index_entry['page_index'] = 0 yield index_path, index_entry else pages = [] n_pages = (items.size + @page_size - 1) / @page_size for num in 0...n_pages page_items = items[@page_size * num, @page_size] entry = index_entry.dup entry['items'] = page_items entry['prev_page'] = "#{num}" entry['next_page'] = "#{num+2}" entry['pages'] = pages entry['page_index'] = num pages << {'path' => "#{index_path}/#{num+1}", 'entry' => entry} end pages[0]['path'] = index_path pages[0]['entry'].delete('prev_page') if pages.size > 1 index_name = index_path.split('/').last pages[0]['entry']['next_page'] = "#{index_name}/2" pages[1]['entry']['prev_page'] = "../#{index_name}" end pages[-1]['entry'].delete('next_page') pages.each do |page| yield page['path'], page['entry'] end end end self end end end end