Sha256: 8624e5bbbcfe49a7a6ba5b3b552fedec6bf101f23391755a607e74df5cac2b74

Contents?: true

Size: 1.52 KB

Versions: 1

Compression:

Stored size: 1.52 KB

Contents

module Jekyll
  class Pager
    attr_reader :page, :per_page, :posts, :total_posts, :total_pages, :previous_page, :next_page
    
    def self.calculate_pages(all_posts, per_page = Jekyll.paginate)
      num_pages = all_posts.size / per_page.to_i
      num_pages.abs + 1 if all_posts.size % per_page.to_i != 0
    end
    
    def self.pagination_enabled?(base, file)
      File.basename(file) == 'index.html' &&
          (!Jekyll.paginate.nil? || 
          (File.yaml?(File.join(base, file)) && 
          Page.new(base, '', file).data.key?('paginate')))
    end
    
    def initialize(page, all_posts, num_pages = nil, per_page = nil)
      @page = page
      @per_page = per_page || Jekyll.paginate
      @total_pages = num_pages || Pager.calculate_pages(all_posts)
      
      if @page > @total_pages
        raise RuntimeError, "page number can't be grater than total pages: #{@page} > #{@total_pages}"
      end
      
      init = (@page - 1) * @per_page
      offset = (init + @per_page - 1) >= all_posts.size ? all_posts.size : (init + @per_page - 1)
      
      @total_posts = all_posts.size
      @posts = all_posts[init..offset]
      @previous_page = @page != 1 ? @page - 1 : nil
      @next_page = @page != @total_pages ? @page + 1 : nil
    end
    
    def to_hash
      {
        'page' => page, 
        'per_page' => per_page, 
        'posts' => posts, 
        'total_posts' => total_posts,
        'total_pages' => total_pages,
        'previous_page' => previous_page,
        'next_page' => next_page
      }
    end
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
calavera-jekyll-0.4.1 lib/jekyll/pager.rb