Optimize ratings calculation

This commit is contained in:
Petko Bordjukov 2016-10-06 20:30:28 +03:00
parent 52cd3716c1
commit 485116e29c
4 changed files with 13 additions and 19 deletions

View File

@ -5,7 +5,7 @@ class HomeController < ApplicationController
def ratings
@talks = Talk.ordered_by_rating
@ratings = Ratings.new
@votes_count = TalkPreference.count
@votes_count = TalkPreference.this_years.count
end
def export

View File

@ -1,16 +1,9 @@
class Ratings
@ratings = Hash.new(0)
def initialize
ratings = TalkPreference.all.pluck(:talks).reduce(Hash.new(0)) do |result, talks|
talks.map(&:to_i).each { |talk| result[talk] += 1 }
result
end.to_h
@ratings = Hash.new(0).merge!(ratings)
@ratings = {}
end
def [](id)
@ratings[id]
@ratings[id] ||= SelectedTalk.where(talk_id: id).count
end
end

View File

@ -1,8 +0,0 @@
<tr>
<td><%= talk.id %></td>
<td><%= talk.event_type.name %></td>
<td><%= talk.title %></td>
<td><%= talk.subtitle %></td>
<td><%= @ratings[talk.id] %></td>
<td><%= "%.2f%" % Rational(100 * @ratings[talk.id], @votes_count).to_f %></td>
</tr>

View File

@ -10,6 +10,15 @@
</tr>
</thead>
<tbody>
<%= render partial: 'talk', collection: @talks %>
<% @talks.each do |talk| %>
<tr>
<td><%= talk.id %></td>
<td><%= talk.event_type.name %></td>
<td><%= talk.title %></td>
<td><%= talk.subtitle %></td>
<td><%= @ratings[talk.id] %></td>
<td><%= "%.2f%" % Rational(100 * @ratings[talk.id], @votes_count).to_f %></td>
</tr>
<% end %>
</tbody>
</table>