Ruby On Rails, Design, Simplicity, Web 2.0, Ajax, Mac and Tons of Pizza.

Jan 24

Howto paginate an Array

Posted by Sandro Paganotti in Ruby on Rails - comments are closed digg this add to delicious

Sometimes could happen that we need to paginate something different from a collection, I found this very useful method that acts similar to a paginate but it works for Arrays ( and Hashes )


  def paginate_collection(collection, options = {})
    default_options = {:per_page => 10, :page => 1}
    options = default_options.merge options

    pages = Paginator.new self, collection.size, options[:per_page], options[:page]
    first = pages.current.offset
    last = [first + options[:per_page], collection.size].min
    slice = collection[first...last]
    return [pages, slice]
  end

I really don’t know who is the author, so please if you are the author post a comment.

Sandro

Comments

  • Paul

    Posted on January 25

    Very nice article. thanks!
  • judith

    Posted on January 29

    Is there any way to determine how many recent comments it displays?

Post a comment

Categories:

Tags:

Powered by Mephisto, Valid XHTML 1.1, Valid CSS - Supported by Wave Factory