Class: Rating

Inherits:
Object
  • Object
show all
Includes:
MongoMapper::Document
Defined in:
lib/acts_as_mongo_rateable/app/models/rating.rb

Instance Method Summary collapse

Instance Method Details

#find_rated_documentObject

Various Instance Methods



59
60
61
62
# File 'lib/acts_as_mongo_rateable/app/models/rating.rb', line 59

def find_rated_document
  klass = rateable_class.constantize
  klass.find(rateable_id.to_s)
end

#find_rated_document!Object



64
65
66
67
68
# File 'lib/acts_as_mongo_rateable/app/models/rating.rb', line 64

def find_rated_document!
  doc = find_rated_document
  raise "Associated document not found" if doc.nil?
  doc
end

#reduce_rating_statsObject



47
48
49
50
51
52
53
54
55
# File 'lib/acts_as_mongo_rateable/app/models/rating.rb', line 47

def reduce_rating_stats
  doc = find_rated_document
  return if doc.nil?
  count = (doc.rating_stats[:count] -= 1)
  doc.rating_stats[:total] -= (value * weight)
  doc.rating_stats[:sum_of_weights] -= weight
  doc.rating_stats[:average] = nil if count == 0
  doc.save
end

#set_previous_valueObject



33
34
35
36
# File 'lib/acts_as_mongo_rateable/app/models/rating.rb', line 33

def set_previous_value
  rating_from_db = Rating.find_by_id(id)
  previous_value = (rating_from_db.value * weight) if rating_from_db
end

#set_rating_statsObject



24
25
26
27
28
29
30
31
# File 'lib/acts_as_mongo_rateable/app/models/rating.rb', line 24

def set_rating_stats
  doc = find_rated_document!
  count = (doc.rating_stats[:count] += 1)
  total = (doc.rating_stats[:total] += ( value * weight ))
  sow = (doc.rating_stats[:sum_of_weights] += weight)
  doc.rating_stats[:average] = total.to_f / sow
  doc.save!
end

#update_rating_statsObject



38
39
40
41
42
43
44
45
# File 'lib/acts_as_mongo_rateable/app/models/rating.rb', line 38

def update_rating_stats
  doc = find_rated_document!
  value_delta = (value * weight) - (previous_value * weight)
  total = (doc.rating_stats[:total] += value_delta)
  count = doc.rating_stats[:count]
  doc.rating_stats[:average] = total.to_f / count
  doc.save
end