Skip to content

Instantly share code, notes, and snippets.

@lukemelia
Created January 17, 2010 06:59
Show Gist options
  • Star 10 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save lukemelia/279256 to your computer and use it in GitHub Desktop.
Save lukemelia/279256 to your computer and use it in GitHub Desktop.
require 'redis'
# SADD key, member
# Adds the specified <i>member</i> to the set stored at <i>key</i>.
redis = Redis.new
redis.sadd 'my_set', 'foo' # => true
redis.sadd 'my_set', 'bar' # => true
redis.sadd 'my_set', 'bar' # => false
redis.smembers 'my_set' # => ["foo", "bar"]
# SUNION key1 key2 ... keyN
# Returns the members of a set resulting from the union of all the sets stored at the specified keys.
# SUNIONSTORE <i>dstkey key1 key2 ... keyN</i></b>
# Works like SUNION but instead of being returned the resulting set is stored as dstkey.
redis = Redis.new
redis.sadd 'set_a', 'foo'
redis.sadd 'set_a', 'bar'
redis.sadd 'set_b', 'bar'
redis.sadd 'set_b', 'baz'
redis.sunion 'set_a', 'set_b' # => ["foo", "baz", "bar"]
redis.sunionstore 'set_ab', 'set_a', 'set_b'
redis.smembers 'set_ab' # => ["foo", "baz", "bar"]
# SINTER key1 key2 ... keyN
# Returns the members that are present in all sets stored at the specified keys.
redis = Redis.new
redis.sadd 'set_a', 'foo'
redis.sadd 'set_a', 'bar'
redis.sadd 'set_b', 'bar'
redis.sadd 'set_b', 'baz'
redis.sinter 'set_a', 'set_b' # => ["bar"]
# Defining the keys
def current_key
key(Time.now.strftime("%M"))
end
def keys_in_last_5_minutes
now = Time.now
times = (0..5).collect {|n| now - n.minutes }
times.collect{ |t| key(t.strftime("%M")) }
end
def key(minute)
"online_users_minute_#{minute}"
end
# Tracking an Active User
def track_user_id(id)
key = current_key
redis.sadd(key, id)
end
# Who's online
def online_user_ids
redis.sunion(*keys_in_last_5_minutes)
end
def online_friend_ids(interested_user_id)
redis.sunionstore("online_users", *keys_in_last_5_minutes)
redis.sinter("online_users", "user:#{interested_user_id}:friend_ids")
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment