2014-08-23 09:45:32 +09:00
|
|
|
module Post::CountMethods
|
2010-04-20 23:05:11 +00:00
|
|
|
module ClassMethods
|
|
|
|
def fast_count(tags = nil)
|
2012-05-10 03:04:05 -07:00
|
|
|
# A small sanitation
|
|
|
|
tags = tags.to_s.strip.gsub(/ +/, ' ')
|
2012-05-10 15:01:03 +00:00
|
|
|
cache_version = Rails.cache.read("$cache_version").to_i
|
2012-07-11 07:44:26 -07:00
|
|
|
key = { :post_count => tags, :v => cache_version }
|
2010-04-20 23:05:11 +00:00
|
|
|
|
2012-05-10 15:01:03 +00:00
|
|
|
count = Rails.cache.fetch(key) {
|
2010-04-20 23:05:11 +00:00
|
|
|
Post.count_by_sql(Post.generate_sql(tags, :count => true))
|
|
|
|
}.to_i
|
|
|
|
|
|
|
|
return count
|
|
|
|
|
|
|
|
# This is just too brittle, and hard to make work with other features that may
|
|
|
|
# hide posts from the index.
|
|
|
|
# if tags.blank?
|
|
|
|
# return select_value_sql("SELECT row_count FROM table_data WHERE name = 'posts'").to_i
|
|
|
|
# else
|
|
|
|
# c = select_value_sql("SELECT post_count FROM tags WHERE name = ?", tags).to_i
|
|
|
|
# if c == 0
|
|
|
|
# return Post.count_by_sql(Post.generate_sql(tags, :count => true))
|
|
|
|
# else
|
|
|
|
# return c
|
|
|
|
# end
|
|
|
|
# end
|
|
|
|
end
|
|
|
|
|
|
|
|
def recalculate_row_count
|
|
|
|
execute_sql("UPDATE table_data SET row_count = (SELECT COUNT(*) FROM posts WHERE parent_id IS NULL AND status <> 'deleted') WHERE name = 'posts'")
|
|
|
|
end
|
|
|
|
end
|
|
|
|
|
|
|
|
def self.included(m)
|
|
|
|
m.extend(ClassMethods)
|
|
|
|
m.after_create :increment_count
|
2012-05-08 07:19:28 +00:00
|
|
|
m.set_callback :delete, :after, :decrement_count
|
|
|
|
m.set_callback :undelete, :after, :increment_count
|
2010-04-20 23:05:11 +00:00
|
|
|
end
|
|
|
|
|
|
|
|
def increment_count
|
|
|
|
execute_sql("UPDATE table_data SET row_count = row_count + 1 WHERE name = 'posts'")
|
|
|
|
end
|
|
|
|
|
|
|
|
def decrement_count
|
|
|
|
execute_sql("UPDATE table_data SET row_count = row_count - 1 WHERE name = 'posts'")
|
|
|
|
end
|
|
|
|
end
|