Separate query from cloud

This will make testing easier
This commit is contained in:
Katrina Owen 2013-03-01 13:14:27 -05:00
parent 8f42b25e68
commit a81f5b76f3
3 changed files with 46 additions and 38 deletions

View file

@ -552,8 +552,11 @@ class StatsController < ApplicationController
end
def get_stats_tags
@tag_cloud = Stats::TagCloud.new(current_user)
@tag_cloud_90days = Stats::TagCloud.new(current_user, @cut_off_3months)
tags = Stats::TagCloudQuery.new(current_user).result
@tag_cloud = Stats::TagCloud.new(tags)
tags_90days = Stats::TagCloudQuery.new(current_user, @cut_off_3months).result
@tag_cloud_90days = Stats::TagCloud.new(tags_90days)
end
def get_ids_from (actions, week_from, week_to, at_end)

View file

@ -3,11 +3,10 @@
module Stats
class TagCloud
attr_reader :user, :cutoff, :levels
def initialize(user, cutoff = nil)
@user = user
@cutoff = cutoff
attr_reader :levels, :tags
def initialize(tags)
@levels = 10
@tags = tags.sort_by { |tag| tag.name.downcase }
end
def empty?
@ -18,10 +17,6 @@ module Stats
(9 + 2*(tag.count.to_i-min)/divisor)
end
def tags
@tags ||= top_tags
end
private
def max
@ -39,33 +34,5 @@ module Stats
def counts
@counts ||= tags.map {|t| t.count.to_i}
end
def top_tags
Tag.find_by_sql(query_options).sort_by { |tag| tag.name.downcase }
end
def query_options
options = [sql, user.id]
options += [cutoff, cutoff] if cutoff
options
end
def sql
# TODO: parameterize limit
query = "SELECT tags.id, tags.name AS name, count(*) AS count"
query << " FROM taggings, tags, todos"
query << " WHERE tags.id = tag_id"
query << " AND todos.user_id=? "
query << " AND taggings.taggable_type='Todo' "
query << " AND taggings.taggable_id=todos.id "
if cutoff
query << " AND (todos.created_at > ? OR "
query << " todos.completed_at > ?) "
end
query << " GROUP BY tags.id, tags.name"
query << " ORDER BY count DESC, name"
query << " LIMIT 100"
end
end
end

View file

@ -0,0 +1,38 @@
module Stats
class TagCloudQuery
attr_reader :user, :cutoff
def initialize(user, cutoff = nil)
@user = user
@cutoff = cutoff
end
def result
Tag.find_by_sql(query_options)
end
def query_options
options = [sql, user.id]
options += [cutoff, cutoff] if cutoff
options
end
def sql
# TODO: parameterize limit
query = "SELECT tags.id, tags.name AS name, count(*) AS count"
query << " FROM taggings, tags, todos"
query << " WHERE tags.id = tag_id"
query << " AND todos.user_id=? "
query << " AND taggings.taggable_type='Todo' "
query << " AND taggings.taggable_id=todos.id "
if cutoff
query << " AND (todos.created_at > ? OR "
query << " todos.completed_at > ?) "
end
query << " GROUP BY tags.id, tags.name"
query << " ORDER BY count DESC, name"
query << " LIMIT 100"
end
end
end