From 4dff7538eab1690c8271f7a7b1d9d0d17a65d564 Mon Sep 17 00:00:00 2001 From: Katrina Owen Date: Fri, 1 Mar 2013 21:27:58 -0500 Subject: [PATCH] Extract duplicated query This includes a bit of a simplification which assumes that there aren't any orphan taggings for a user. --- app/controllers/stats_controller.rb | 27 +++------------------------ app/models/stats/user_tags_query.rb | 26 ++++++++++++++++++++++++++ 2 files changed, 29 insertions(+), 24 deletions(-) create mode 100644 app/models/stats/user_tags_query.rb diff --git a/app/controllers/stats_controller.rb b/app/controllers/stats_controller.rb index 5512abad..44c7787b 100644 --- a/app/controllers/stats_controller.rb +++ b/app/controllers/stats_controller.rb @@ -9,8 +9,9 @@ class StatsController < ApplicationController @page_title = t('stats.index_title') @first_action = current_user.todos.reorder("created_at ASC").first - @tags_count = get_total_number_of_tags_of_user - @unique_tags_count = get_unique_tags_of_user.size + tag_ids = Stats::UserTagsQuery.new(current_user).result.map(&:id) + @tags_count = tag_ids.size + @unique_tags_count = tag_ids.uniq.size @hidden_contexts = current_user.contexts.hidden get_stats_actions @@ -396,28 +397,6 @@ class StatsController < ApplicationController @truncate_chars = 15 end - def get_unique_tags_of_user - tag_ids = current_user.todos.find_by_sql([ - "SELECT DISTINCT tags.id as id "+ - "FROM tags, taggings, todos "+ - "WHERE tags.id = taggings.tag_id " + - "AND taggings.taggable_id = todos.id "+ - "AND todos.user_id = #{current_user.id}"]) - tags_ids_s = tag_ids.map(&:id).sort.join(",") - return {} if tags_ids_s.blank? # return empty hash for .size to work - return Tag.where("id in (#{tags_ids_s})") - end - - def get_total_number_of_tags_of_user - # same query as get_unique_tags_of_user except for the DISTINCT - return current_user.todos.find_by_sql([ - "SELECT tags.id as id "+ - "FROM tags, taggings, todos "+ - "WHERE tags.id = taggings.tag_id " + - "AND taggings.taggable_id = todos.id " + - "AND todos.user_id = #{current_user.id}"]).size - end - def init @me = self # for meta programming diff --git a/app/models/stats/user_tags_query.rb b/app/models/stats/user_tags_query.rb new file mode 100644 index 00000000..034e5adb --- /dev/null +++ b/app/models/stats/user_tags_query.rb @@ -0,0 +1,26 @@ +module Stats + class UserTagsQuery + + attr_reader :user + def initialize(user) + @user = user + end + + def result + user.todos.find_by_sql([sql, user.id]) + end + + private + + def sql + <<-SQL + SELECT tags.id as id + FROM tags, taggings, todos + WHERE tags.id = taggings.tag_id + AND taggings.taggable_id = todos.id + AND todos.user_id = ? + SQL + end + + end +end