1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45
def custom_pagination(num_item, per_page, current_page) num_page = (num_item/per_page.to_f).ceil arr_page = [] range_separator = "..." if current_page < 1 current_page = 1 elsif current_page > num_page current_page = num_page end if num_page <= 15 1.upto(num_page){|n| arr_page.push(n)} else if current_page <= 7 or current_page >= (num_page-7) 1.upto(7){|n| arr_page.push(n)} arr_page.push(range_separator) (num_page-7).upto(num_page){|n| arr_page.push(n)} elsif current_page > 7 and current_page < 14 1.upto(current_page){|n| arr_page.push(n) } arr_page.push(range_separator) (num_page-(15-arr_page.size)).upto(num_page){|n| arr_page.push(n)} elsif (current_page > num_page-14 and current_page < num_page-7) current_page.upto(num_page){|n| arr_page.push(n)} arr_page.unshift(range_separator) (15-arr_page.size).downto(1){|n| arr_page.unshift(n)} arr_page.reverse! else arr_page.push(1) arr_page.push(range_separator) (current_page-5).upto(current_page+5){|n| arr_page.push(n)} arr_page.push(range_separator) arr_page.push(num_page) end end arr_page.reverse! if arr_page.first > arr_page.last arr_page end #custom_pagination(186, 10, 3) #custom_pagination(186, 10, 18) #custom_pagination(186, 10, 11) #custom_pagination(286, 10, 18) custom_pagination(146, 10, 1)
Refactorings
No refactoring yet !
Joe Grossberg
September 8, 2008, September 08, 2008 14:53, permalink
First thing:
Don't use "magic numbers". Separate them out into meaningful variable names (like what you did with range_separator = "...") or parameters. For example:
1 2 3 4 5 6 7 8 9 10 11 12 13
def custom_pagination(num_item, per_page, current_page, max_pages=15) # ... if num_page <= max_pages # ... OR def custom_pagination(num_item, per_page, current_page) # ... max_pages = 15 # ... if num_page <= max_pages # ...
Hello everybody,
I'm beginner in programming, especially in ruby.
I've created method that return array of page for Rails ActiveRecord object pagination,
for some reason i don't use any rails plugin to implement it.
The method parameters are num item to paginate, num item per page and current page,
and the returned value is an array of page.
My code is bad, and i'm sure that there are some simple ways better than my code.
Could anyone help me?
Thanks before,
Dimas Priyanto