diff --git a/spec/paginator/paginator_spec.cr b/spec/paginator/paginator_spec.cr index b034f30ce..4d7d77bab 100644 --- a/spec/paginator/paginator_spec.cr +++ b/spec/paginator/paginator_spec.cr @@ -92,6 +92,24 @@ describe Lucky::Paginator do end end + describe "#previous_page" do + it "returns the next page" do + build_pages(page: 0, per_page: 3, item_count: 10).previous_page.should be_nil + build_pages(page: 1, per_page: 3, item_count: 10).previous_page.should be_nil + build_pages(page: 3, per_page: 3, item_count: 10).previous_page.should eq(2) + build_pages(page: 4, per_page: 3, item_count: 10).previous_page.should eq(3) + end + end + + describe "#next_page" do + it "returns the next page" do + build_pages(page: 1, per_page: 3, item_count: 10).next_page.should eq(2) + build_pages(page: 3, per_page: 3, item_count: 10).next_page.should eq(4) + build_pages(page: 4, per_page: 3, item_count: 10).next_page.should be_nil + build_pages(page: 9, per_page: 3, item_count: 10).next_page.should be_nil + end + end + describe "#path_to_page" do it "adds a query param to the path" do path = build_pages(full_path: "/comments").path_to_page(1) diff --git a/src/lucky/paginator/paginator.cr b/src/lucky/paginator/paginator.cr index 2db1168bd..2a6808ea9 100644 --- a/src/lucky/paginator/paginator.cr +++ b/src/lucky/paginator/paginator.cr @@ -61,12 +61,22 @@ class Lucky::Paginator Range.new(starting_item_number, ending_item_number) end + # Returns the previous page number or nil if the current page is the first one. + def previous_page : Int32? + page - 1 unless first_page? + end + + # Returns the next page number or nil if the current page is the last one. + def next_page : Int32? + page + 1 unless last_page? || overflowed? + end + # Returns the path with a 'page' query param for the previous page. # # Return nil if there is no previous page def path_to_previous : String? - unless first_page? - path_to_page(page - 1) + if page_number = previous_page + path_to_page(page_number) end end @@ -74,8 +84,8 @@ class Lucky::Paginator # # Return nil if there is no previous page def path_to_next : String? - unless last_page? - path_to_page(page + 1) + if page_number = next_page + path_to_page(page_number) end end