Class: Rating::Rating

Inherits:
ActiveRecord::Base
  • Object
show all
Defined in:
lib/rating/models/rating/rating.rb

Class Method Summary collapse

Class Method Details

.data(resource, scopeable) ⇒ Object



42
43
44
45
46
47
48
49
50
51
52
# File 'lib/rating/models/rating/rating.rb', line 42

def data(resource, scopeable)
  histogram = histogram_data(resource, scopeable)
  values = values_data(resource, scopeable)

  {
    average:  values.rating_avg,
    estimate: miller_lower_bound(histogram),
    sum:      values.rating_sum,
    total:    values.rating_count,
  }
end

.histogram_data(resource, scopeable) ⇒ Object



20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
# File 'lib/rating/models/rating/rating.rb', line 20

def histogram_data(resource, scopeable)
  sql = %(
    SELECT
      value,
      COUNT(1) AS rating_count
    FROM #{rate_table_name}
    WHERE
      resource_type = ?
      AND resource_id = ?
      #{scope_type_and_id_query(resource, scopeable)}
      #{scope_where_query(resource)}
    GROUP BY value
  ).squish

  values = [sql, resource.class.base_class.name, resource.id]
  values += [scopeable.class.base_class.name, scopeable.id] unless scopeable.nil? || unscoped_rating?(resource)

  Rate.find_by_sql(values).to_h do |row|
    [row.value.to_i, row.rating_count.to_i]
  end
end

.update_rating(resource, scopeable) ⇒ Object



74
75
76
77
78
79
80
81
82
83
84
85
86
87
# File 'lib/rating/models/rating/rating.rb', line 74

def update_rating(resource, scopeable)
  attributes = { resource: }
  attributes[:scopeable] = unscoped_rating?(resource) ? nil : scopeable

  record = find_or_initialize_by(attributes)
  result = data(resource, scopeable)

  record.average = result[:average]
  record.sum = result[:sum]
  record.total = result[:total]
  record.estimate = result[:estimate]

  record.save
end

.values_data(resource, scopeable) ⇒ Object



54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
# File 'lib/rating/models/rating/rating.rb', line 54

def values_data(resource, scopeable)
  sql = %(
    SELECT
      COALESCE(AVG(value), 0) rating_avg,
      COALESCE(SUM(value), 0) rating_sum,
      COUNT(1)                rating_count
    FROM #{rate_table_name}
    WHERE
      resource_type = ?
      AND resource_id = ?
      #{scope_type_and_id_query(resource, scopeable)}
      #{scope_where_query(resource)}
  ).squish

  values = [sql, resource.class.base_class.name, resource.id]
  values += [scopeable.class.base_class.name, scopeable.id] unless scopeable.nil? || unscoped_rating?(resource)

  execute_sql values
end