Skip to content

Instantly share code, notes, and snippets.

@mrichie
Forked from HungYuHei/Gemfile
Created October 30, 2012 08:15
Show Gist options
  • Save mrichie/3978923 to your computer and use it in GitHub Desktop.
Save mrichie/3978923 to your computer and use it in GitHub Desktop.
followable with redis Sorted-Set
# Gemfile
gem 'redis', '~> 3.0.1'
# config/initializers/redis.rb
$redis = Redis.new(:host => 'localhost', :port => 6379)
# app/models/user.rb
class User
def follow(user)
score = Time.now.to_i
$redis.multi do
$redis.zadd(friendship_redis_key(:following), score, followed.id)
$redis.zadd(followed.friendship_redis_key(:followers), score, id)
end
end
def unfollow(user)
$redis.multi do
$redis.zrem(friendship_redis_key(:following), user.id)
$redis.zrem(user.friendship_redis_key(:followers), id)
end
end
def followers
User.where(:id => follower_ids)
end
def following
User.where(:id => following_ids)
end
def follower_ids
$redis.zrevrange(friendship_redis_key(:followers), 0, -1)
end
def following_ids
$redis.zrevrange(friendship_redis_key(:following), 0, -1)
end
def following?(user)
!$redis.zscore(friendship_redis_key(:following), user.id).nil?
end
def followed_by?(user)
!$redis.zscore(friendship_redis_key(:followers), user.id).nil?
end
def followers_count
$redis.zcard(friendship_redis_key(:followers))
end
def following_count
$redis.zcard(friendship_redis_key(:following))
end
private
# generate redis keys
def friendship_redis_key(str)
"user:#{id}:#{str}"
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment