Permalink
Browse files

Added percentile_for(member) and percentile_for_in(leaderboard_name, …

…member) methods to calculate percentile for a given member
  • Loading branch information...
1 parent a8202e9 commit 4f7730be3e263d2ab9fe6ea67fb60d74bb42b813 @czarneckid czarneckid committed Oct 15, 2011
Showing with 24 additions and 0 deletions.
  1. +1 −0 CHANGELOG.markdown
  2. +13 −0 lib/leaderboard.rb
  3. +10 −0 test/test_leaderboard.rb
View
@@ -1,6 +1,7 @@
# leaderboard 2.0.1
* Allow for only single options to be passed to `leaders`, `around_me` and `ranked_in_list` methods - https://github.com/agoragames/leaderboard/issues/4
+ * Added `percentile_for(member)` and `percentile_for_in(leaderboard_name, member)` methods to calculate percentile for a given member
# leaderboard 2.0.0 (2011-08-05)
View
@@ -162,6 +162,19 @@ def remove_members_in_score_range_in(leaderboard_name, min_score, max_score)
@redis_connection.zremrangebyscore(leaderboard_name, min_score, max_score)
end
+ def percentile_for(member)
+ percentile_for_in(@leaderboard_name, member)
+ end
+
+ def percentile_for_in(leaderboard_name, member)
+ responses = @redis_connection.multi do |transaction|
+ transaction.zcard(leaderboard_name)
+ transaction.zrevrank(leaderboard_name, member)
+ end
+
+ ((responses[0] - responses[1] - 1).to_f / responses[0].to_f * 100).ceil
+ end
+
def leaders(current_page, options = {})
leaders_in(@leaderboard_name, current_page, options)
end
@@ -409,6 +409,16 @@ def test_around_me_call_with_new_page_size
assert_equal 'member_29', leaders_around_me[2][:member]
end
+ def test_percentile_for
+ rank_members_in_leaderboard(12)
+
+ assert_equal 0, @leaderboard.percentile_for('member_1')
+ assert_equal 9, @leaderboard.percentile_for('member_2')
+ assert_equal 17, @leaderboard.percentile_for('member_3')
+ assert_equal 25, @leaderboard.percentile_for('member_4')
+ assert_equal 92, @leaderboard.percentile_for('member_12')
+ end
+
private
def rank_members_in_leaderboard(members_to_add = 5)

0 comments on commit 4f7730b

Please sign in to comment.