-
-
Save reddyonrails/e7decf3ca2104fb0062d8a8d69a39c23 to your computer and use it in GitHub Desktop.
Redis Nested Comments in Ruby
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #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