diff --git a/app/controllers/polls/stats_controller.rb b/app/controllers/polls/stats_controller.rb new file mode 100644 index 000000000..4d6a40ff3 --- /dev/null +++ b/app/controllers/polls/stats_controller.rb @@ -0,0 +1,20 @@ +class Polls::StatsController < ApplicationController + + before_action :load_poll + load_and_authorize_resource :poll + + def show + authorize! :read_stats, @poll + @stats = load_stats + end + + private + + def load_stats + Poll::Stats.new(@poll).generate + end + + def load_poll + @poll = Poll.find_by(id: params[:id]) + end +end \ No newline at end of file diff --git a/app/models/abilities/everyone.rb b/app/models/abilities/everyone.rb index 3004ca8ad..73f3220ab 100644 --- a/app/models/abilities/everyone.rb +++ b/app/models/abilities/everyone.rb @@ -23,6 +23,7 @@ module Abilities can [:read], Legislation::Question can [:create], Legislation::Answer can [:search, :comments, :read, :create, :new_comment], Legislation::Annotation + can :read_stats, Poll end end end diff --git a/app/models/poll/stats.rb b/app/models/poll/stats.rb new file mode 100644 index 000000000..823724ade --- /dev/null +++ b/app/models/poll/stats.rb @@ -0,0 +1,36 @@ +class Poll + class Stats + + def initialize(poll) + @poll = poll + end + + def generate + stats = %w[total_participants total_participants_web total_participants_booth] + stats.map { |stat_name| [stat_name.to_sym, send(stat_name)] }.to_h + end + + private + + def total_participants + stats_cache('total_participants') { voters.uniq.count } + end + + def total_participants_web + stats_cache('total_participants_web') { voters.where(origin: 'web').count } + end + + def total_participants_booth + stats_cache('total_participants_booth') { voters.where(origin: 'booth').count } + end + + def voters + stats_cache('voters') { @poll.voters } + end + + def stats_cache(key, &block) + Rails.cache.fetch("polls_stats/#{@poll.id}/#{key}/v7", &block) + end + + end +end \ No newline at end of file diff --git a/app/views/polls/show.html.erb b/app/views/polls/show.html.erb index 0a56ba237..2c541305d 100644 --- a/app/views/polls/show.html.erb +++ b/app/views/polls/show.html.erb @@ -28,6 +28,8 @@ + + <%= link_to "Estadísticas", custom_poll_stats_path(@poll.id) %>
+ <%= @stats[:total_participants] %> +
+| Web | +Booth | +
| <%= @stats[:total_participants_web] %> | +<%= @stats[:total_participants_booth] %> | +
+ <%= @stats[:total_votes] %> +
+