lib/models.rb in cachai-0.1.4 vs lib/models.rb in cachai-0.2.0
- old
+ new
@@ -50,9 +50,45 @@
def self.key_for(path)
raise "Domain not set!" unless @domain
"comments:#{@domain}:#{path}"
end
+ def self.get_comments_for(path, nocache = false)
+ key = key_for(path)
+
+ unless !nocache && json_list = cache.get(key)
+ # puts "Not cached. Getting from DB: #{path}"
+
+ if post = Post.find_by_path(path)
+ json_list = get_and_sort_comments_for(post).to_json
+ else
+ json_list = '[]'
+ end
+
+ cache.set(key, json_list)
+ cache.expire(key, CACHE_MINUTES)
+ end
+
+ json_list
+ end
+
+ def self.get_and_sort_comments_for(post)
+ result = []
+ top_level = post.responses.comment.approved.top_level
+ nested = post.responses.comment.approved.nested
+
+ top_level.each_with_index do |comment, i|
+ obj = comment.as_json
+ children = nested.select do |nested|
+ nested.parent_id == comment.id
+ end
+ obj.merge!(:children => children) if children.any?
+ result.push(obj)
+ end
+
+ result
+ end
+
class Post < ActiveRecord::Base
has_many :responses
validates_presence_of :path
validates_uniqueness_of :path