Skip to content
Snippets Groups Projects
review.rb 2.65 KiB
Newer Older
bfs15's avatar
bfs15 committed

# Copyright (C) 2015 Centro de Computacao Cientifica e Software Livre
# Departamento de Informatica - Universidade Federal do Parana
#
# This file is part of portalmec.
#
# portalmec is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# portalmec is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with portalmec.  If not, see <http://www.gnu.org/licenses/>.

# == Schema Information
#
# Table name: reviews
#
#  id              :integer          not null, primary key
#  name            :string
#  description     :text
#  pros            :text
#  cons            :text
#  reviewable_id   :integer
#  reviewable_type :string
#  user_id         :integer
#  created_at      :datetime         not null
#  updated_at      :datetime         not null
#  rates_count     :integer          default("0")
#

Mateus Rambo Strey's avatar
Mateus Rambo Strey committed
class Review < ApplicationRecord
  # *current_user* review *reviewable*
  include Trackable
  after_save :calculate_review_rate
  after_destroy :calculate_review_rate
  belongs_to :reviewable, polymorphic: true
  has_many :review_ratings
  has_many :ratings, through: :review_ratings
  has_many :rates
Mateus Rambo Strey's avatar
Mateus Rambo Strey committed
  validates_presence_of :user, :reviewable
Mateus Rambo Strey's avatar
Mateus Rambo Strey committed
  validates_inclusion_of :reviewable_type, in: %w(LearningObject Collection), message: 'Only LearningObjects and Collections are reviewable.'
  validates_uniqueness_of :user, scope: [:reviewable_id, :reviewable_type]
  accepts_nested_attributes_for :review_ratings

  def rating_values
Mateus Rambo Strey's avatar
Mateus Rambo Strey committed
    review_ratings.includes(:rating).map { |r| { rating: r.rating, value: r.value } }
  def rating_average
Mateus Rambo Strey's avatar
Mateus Rambo Strey committed
    return 0.0 if review_ratings.empty?
    review_ratings.average(:value).floor(1).to_f
  end

  def rates_percentage
    return 0.0 if rates.count < 5
    approved = rates.where(approves: true).count
    (approved.to_f / rates.count.to_f) * 100
  end

  def rated?(user)
    !Rate.find_by(user: user, review: self).nil?
  def user_approves?(user)
    return Rate.find_by(user: user, review: self).approves if rated? user

  private

  def calculate_review_rate
    ReviewAverageCalculatorWorker.perform_in(1.minutes, reviewable.id, reviewable.class.name)