Guest User

Untitled

a guest
Jul 23rd, 2018
113
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.62 KB | None | 0 0
  1. class Score
  2. include MongoMapper::Document
  3.  
  4. key :user_id, ObjectId, :index => true
  5. key :stage, String, :index => true
  6. key :score, Integer
  7. timestamps!
  8.  
  9. def self.high_score_map
  10. <<-MAP
  11. function() {
  12. emit(this.stage, { user_id : this.user_id, score: this.score });
  13. }
  14. MAP
  15. end
  16.  
  17. def self.high_score_reduce
  18. <<-REDUCE
  19. function(k, v) {
  20. var top = 0;
  21. var user_id = '';
  22. for (var i in v) {
  23. if (v[i]["score"] > top) {
  24. top = v[i]["score"];
  25. user_id = v[i]["user_id"];
  26. }
  27. }
  28. return { user_id: user_id, score: top };
  29. }
  30. REDUCE
  31. end
  32.  
  33. def self.high_score_build(opts)
  34. Score.collection.map_reduce(high_score_map, high_score_reduce, opts).find()
  35. end
  36.  
  37. def self.high_score(opts={})
  38. data = []
  39. Score.high_score_build(opts).each do |score|
  40. data << { :user_id => score["value"]["user_id"], :stage => score["_id"], :score => score["value"]["score"] }
  41. end
  42. data
  43. end
  44.  
  45. def self.high_score_daily(opts={})
  46. opts[:query][:created_at] = { "$gt" => Time.now - 1.day }
  47. Score.high_score(opts)
  48. end
  49.  
  50. def self.high_score_weekly(opts={})
  51. opts[:query][:created_at] = { "$gt" => Time.now - 1.week }
  52. Score.high_score(opts)
  53. end
  54.  
  55. def self.high_score_monthly(opts={})
  56. opts[:query][:created_at] = { "$gt" => Time.now - 1.month }
  57. Score.high_score(opts)
  58. end
  59.  
  60. end
  61.  
  62. class TopScore
  63. include MongoMapper::Document
  64.  
  65. key :_id, String
  66. key :value, Hash
  67.  
  68. def self.compute_top_scores(opts={})
  69. opts[:out] = "top_scores"
  70. Score.high_score(opts)
  71. end
  72.  
  73. end
Add Comment
Please, Sign In to add comment