Module: ActsAsMongoRateable::InstanceMethods

Defined in:
lib/acts_as_mongo_rateable/acts_as_mongo_rateable.rb

Instance Method Summary collapse

Instance Method Details

#average_ratingObject



34
35
36
# File 'lib/acts_as_mongo_rateable/acts_as_mongo_rateable.rb', line 34

def average_rating
  rating_stats['average']
end

#bayesian_rating(stats = nil) ⇒ Object



38
39
40
41
42
43
44
45
46
47
# File 'lib/acts_as_mongo_rateable/acts_as_mongo_rateable.rb', line 38

def bayesian_rating(stats=nil)
  return 0 if rating_stats['count'] == 0
  stats ||= self.class.all({:select => 'id, rating_stats'})
  system_counts = stats.map{ |p| [ p.id.to_s, p.rating_stats['count'] ] }
  avg_rating = stats.map{|p| p.rating_stats['average'] || 0 }.sum / stats.size.to_f
  avg_num_votes = system_counts.inject(0){|sum, r| sum += r.to_a.flatten[1] } / system_counts.size.to_f
  my_rating = rating_stats['average'] || 0
  my_count = rating_stats['count']
  ( (avg_num_votes * avg_rating) + (my_count * my_rating) ) / (avg_num_votes + my_count)
end

#delete_all_ratingsObject



30
31
32
# File 'lib/acts_as_mongo_rateable/acts_as_mongo_rateable.rb', line 30

def delete_all_ratings
  ratings.delete_all
end

#delete_ratings_by_user(user) ⇒ Object



49
50
51
52
53
54
# File 'lib/acts_as_mongo_rateable/acts_as_mongo_rateable.rb', line 49

def delete_ratings_by_user(user)
  return false unless user
  return 0 if ratings.blank?
  ratings.delete_all(:user_id => user.id.to_s)
  self.reload
end

#rate(value, user = nil, weight = 1) ⇒ Object



56
57
58
59
60
61
62
63
64
65
66
67
68
69
# File 'lib/acts_as_mongo_rateable/acts_as_mongo_rateable.rb', line 56

def rate(value, user = nil, weight = 1)
  delete_ratings_by_user(user)
  validate_rating!(value)
  r = Rating.new({
    :value => value, 
    :user_id => user.id, 
    :rateable_id => self.id,
    :rateable_class => self.class.to_s,
    :weight => weight
    })
  self.ratings << r
  self.reload
  r
end

#rated_by_user?(user) ⇒ Boolean

returns the Rating object found if user has rated this project, else returns nil

Returns:

  • (Boolean)


72
73
74
75
# File 'lib/acts_as_mongo_rateable/acts_as_mongo_rateable.rb', line 72

def rated_by_user?(user)
  return false unless user
  ratings.detect{ |r| r.user_id == user.id}
end