Extract duplicate context query from controller

This commit is contained in:
Katrina Owen 2013-03-01 23:29:54 -05:00
parent f375c06964
commit a23d2eb070
2 changed files with 36 additions and 25 deletions

View file

@ -464,31 +464,8 @@ class StatsController < ApplicationController
end
def get_stats_contexts
# get action count per context for TOP 5
#
# Went from GROUP BY c.id to c.id, c.name for compatibility with postgresql.
# Since the name is forced to be unique, this should work.
@actions_per_context = current_user.contexts.find_by_sql(
"SELECT c.id AS id, c.name AS name, count(*) AS total "+
"FROM contexts c, todos t "+
"WHERE t.context_id=c.id "+
"AND t.user_id=#{current_user.id} " +
"GROUP BY c.id, c.name ORDER BY total DESC " +
"LIMIT 5"
)
# get incomplete action count per visible context for TOP 5
#
# Went from GROUP BY c.id to c.id, c.name for compatibility with postgresql.
# Since the name is forced to be unique, this should work.
@running_actions_per_context = current_user.contexts.find_by_sql(
"SELECT c.id AS id, c.name AS name, count(*) AS total "+
"FROM contexts c, todos t "+
"WHERE t.context_id=c.id AND t.completed_at IS NULL AND NOT c.state='hidden' "+
"AND t.user_id=#{current_user.id} " +
"GROUP BY c.id, c.name ORDER BY total DESC " +
"LIMIT 5"
)
@actions_per_context = Stats::TopContextsQuery.new(current_user).result
@running_actions_per_context = Stats::TopContextsQuery.new(current_user, :running).result
@context_charts = %w{
context_total_actions_data

View file

@ -0,0 +1,34 @@
# Get action count for the top 5 contexts
# If initialized with :running, then only active
# and visible contexts will be included.
module Stats
class TopContextsQuery
attr_reader :user, :running
def initialize(user, running = nil)
@user = user
@running = running == :running
end
def result
user.contexts.find_by_sql([sql, user.id])
end
private
def sql
query = "SELECT c.id AS id, c.name AS name, count(c.id) AS total "
query << "FROM contexts c, todos t "
query << "WHERE t.context_id=c.id "
query << "AND t.user_id = ? "
if running
query << "AND t.completed_at IS NULL "
query << "AND NOT c.state='hidden' "
end
query << "GROUP BY c.id, c.name "
query << "ORDER BY total DESC "
query << "LIMIT 5"
end
end
end