class FiveStar::RatingCalculator

Calculate overall rating for the rateable object from each rater. Each instance must implement rating and weighting. The configuration instance provides min and max rating and weighting values.

@api private

Attributes

configuration[R]
raters[R]

Public Class Methods

new(configuration, raters) click to toggle source
# File lib/five-star/rating_calculator.rb, line 13
def initialize(configuration, raters)
  @configuration = configuration
  @raters = raters
end
rate(configuration, raters) click to toggle source

@see calculate_rating

# File lib/five-star/rating_calculator.rb, line 9
def self.rate(configuration, raters)
  new(configuration, raters).calculate_rating
end

Public Instance Methods

calculate_rating() click to toggle source

Calculate the overall weighting from each rating class

@return [Float] the calculated rating

The min rating will be returned if there are no raters.

@raise [FiveStar::RatingError] raises error if any raters return either

+rating+ or +weighting+ that is outside of configuration bounds.

@api private

# File lib/five-star/rating_calculator.rb, line 27
def calculate_rating
  return min_rating unless raters.any?

  sum_total / weights_total
end

Private Instance Methods

max_rating() click to toggle source
# File lib/five-star/rating_calculator.rb, line 71
def max_rating
  configuration.max_rating
end
max_weighting() click to toggle source
# File lib/five-star/rating_calculator.rb, line 79
def max_weighting
  configuration.max_weighting
end
min_rating() click to toggle source
# File lib/five-star/rating_calculator.rb, line 67
def min_rating
  configuration.min_rating
end
min_weighting() click to toggle source
# File lib/five-star/rating_calculator.rb, line 75
def min_weighting
  configuration.min_weighting
end
sum_total() click to toggle source
# File lib/five-star/rating_calculator.rb, line 37
def sum_total
  raters.map { |rater|
    validate_rating!(rater.rating, rater) * validate_weighting!(rater.weighting, rater)
  }.reduce(&:+)
end
validate_rating!(rating, rater) click to toggle source
# File lib/five-star/rating_calculator.rb, line 47
def validate_rating!(rating, rater)
  rating = rating.to_f

  if rating < min_rating || rating > max_rating
    raise RatingError, "Rating #{rating} is invalid from #{rater.class}"
  else
    rating
  end
end
validate_weighting!(weighting, rater) click to toggle source
# File lib/five-star/rating_calculator.rb, line 57
def validate_weighting!(weighting, rater)
  weighting = weighting.to_f

  if weighting < min_weighting || weighting > max_weighting
    raise RatingError, "Weighting #{weighting} is invalid from #{rater.class}"
  else
    weighting
  end
end
weights_total() click to toggle source
# File lib/five-star/rating_calculator.rb, line 43
def weights_total
  raters.map(&:weighting).reduce(&:+)
end