Skip to content

Instantly share code, notes, and snippets.

@reddyonrails
Forked from Loupi/nested-redis.rb
Created November 6, 2019 17:59
Show Gist options
  • Select an option

  • Save reddyonrails/e7decf3ca2104fb0062d8a8d69a39c23 to your computer and use it in GitHub Desktop.

Select an option

Save reddyonrails/e7decf3ca2104fb0062d8a8d69a39c23 to your computer and use it in GitHub Desktop.
Redis Nested Comments in Ruby
#based on http://forrst.com/posts/Nested_Comments_system_using_Redis-Ror
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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment