Skip to content

Commit

Permalink
Add previous_page and next_page methods to paginator (#1611)
Browse files Browse the repository at this point in the history
  • Loading branch information
wout authored Nov 15, 2021
1 parent 35309ac commit 03c2eee
Show file tree
Hide file tree
Showing 2 changed files with 32 additions and 4 deletions.
18 changes: 18 additions & 0 deletions spec/paginator/paginator_spec.cr
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
18 changes: 14 additions & 4 deletions src/lucky/paginator/paginator.cr
Original file line number Diff line number Diff line change
Expand Up @@ -61,21 +61,31 @@ 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

# Returns the path with a 'page' query param for the previous page.
#
# 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

Expand Down

0 comments on commit 03c2eee

Please sign in to comment.