From a23d2eb0709bfde7134ac40d39e2293d1bd80094 Mon Sep 17 00:00:00 2001 From: Katrina Owen Date: Fri, 1 Mar 2013 23:29:54 -0500 Subject: [PATCH] Extract duplicate context query from controller --- app/controllers/stats_controller.rb | 27 ++------------------ app/models/stats/top_contexts_query.rb | 34 ++++++++++++++++++++++++++ 2 files changed, 36 insertions(+), 25 deletions(-) create mode 100644 app/models/stats/top_contexts_query.rb diff --git a/app/controllers/stats_controller.rb b/app/controllers/stats_controller.rb index e4e46fb7..964847a0 100644 --- a/app/controllers/stats_controller.rb +++ b/app/controllers/stats_controller.rb @@ -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 diff --git a/app/models/stats/top_contexts_query.rb b/app/models/stats/top_contexts_query.rb new file mode 100644 index 00000000..714af8e1 --- /dev/null +++ b/app/models/stats/top_contexts_query.rb @@ -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