Leaderboards on Rails



Originally published at: http://www.sitepoint.com/leaderboards-rails/

Recently, I had reason to create a Rails app that was a simple leaderboard. My constraints were as follows:

  • Accept a name and a score for a new entry on the board. If the name already exists, update the score with the new value.

  • Return a JSON representation for a supplied name, including rank and score.

  • Support HTML and JSON representation of all the entries on the leaderboard. Include the ability to specify page number (default to 0) and offset (default to 10).

  • Do not allow more than 100 records to be returned for a single request.

  • Allow for removal of a specified name from the leaderboard.

All in all, the requirements are pretty straightforward. Basically, allow the user to create, update, and remove entries on the leaderboard. Also, return the current entries, ordered by rank, in either HTML or JSON format.

A quick Google or two later, I knew I wanted to use Redis. This article really articulates how Redis’ features support a leaderboard quite well. Namely, the Redis data type Sorted Set was made for leaderboards. Here are some of the Sorted Set Commands that will be used:

  • ZADD: Add one or more members to the set with the specifed scores. ZADD myzset 2 "two" 3 "three" will add 2 members.

  • ZREVRANGEBYSCORE: Return all the members in the leaderboard found between the supplied min and max values. This is used to show the members from highest to lowest.

  • ZSCORE and ZRANK allow the retrieval of members by score and rank, respectively.

Continue reading this article on SitePoint

closed #2

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.