Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add previous_page and next_page methods to paginator #1611

Merged
merged 1 commit into from
Nov 15, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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