require 'ostruct' require 'redis' require 'securerandom' require 'yaml' class CommentsRepository def initialize @redis = Redis.new end def save itemId, comment, parentId = nil @redis.del "item:#{itemId}:parsedComments" data = hashComment itemId, comment, parentId id = data[:id] if parentId == nil @redis.rpush "item:#{itemId}:comments", id else @redis.hset "comment:#{parentId}", 'hasChildrens', 1 @redis.rpush "thread:#{data[:parentId]}", id end @redis.hmset "comment:#{id}", data.map{|k,v| [k,v]}.flatten(1) id end def get itemId parsedComments = @redis.get "item:#{itemId}:parsedComments" if true#!parsedComments data = multiFetch "item:#{itemId}:comments" parsedComments = processComments data @redis.set "item:#{itemId}:parsedComments", parsedComments.to_yaml else parsedComments = YAML.load parsedComments end parsedComments end private def hashComment itemId, comment, parentId { id: SecureRandom.uuid, itemId: itemId, comment: comment, parentId: parentId == nil ? itemId : parentId, time: Time.now, hasChildrens: 0 } end def multiFetch keyName commentList = @redis.lrange keyName, 0, -1 @redis.multi do |multi| commentList.map { |commentId| multi.hgetall "comment:#{commentId}" } end end def processComments comments result = Hash.new comments.each do |data| data = OpenStruct.new data result[data.id] = data if data.hasChildrens == '1' childData = multiFetch "thread:#{data.id}" data.comments = processComments childData end end result end end