Skip to content

Instantly share code, notes, and snippets.

@kerinin
Created May 2, 2012 21:45
Show Gist options
  • Save kerinin/2580762 to your computer and use it in GitHub Desktop.
Save kerinin/2580762 to your computer and use it in GitHub Desktop.
MessageExpiration
# Stores and retrieves messages to be expired on a given date
#
# Messages can be added, removed, and expired. The actual removal
# of the messages from the user's account is not handled here.
#
class MessageExpiration
attr_reader :eea_id
def inititialize(eea_id)
@eea_id = eea_id
end
# Add messages to be expired on a specific date
#
def record_messages_for_expiry(folder, message_ids, expiration_date)
Array(message_ids).each do |id|
$redis.zadd eea_id, days_since_epoch(expiration_date), member_string(folder, id)
end
end
# Remove messages before their expiration date, preventing
# them fromm being removed. Intended to be used in cases where
# we decide not to expire a message (ex: if a user opens a message)
#
def prevent_expiry(folder, message_ids)
Array(message_ids).each do |id|
$redis.zrem eea_id, member_string(folder, id)
end
end
# Pops messages set to expire by the given date and returns them
# as a hash keyed by folder name.
#
# ex: "OIB/Finance" => [231,5343,343,234,4], "OIB/News" => [234,153]
#
def expire_messages(until_date=DateTime.now)
messages = messages_to_expire(eea_id, until_date)
$redis.zremrangebyscore eea_id, 0, days_since_epoch(until_date)
messages
end
# Private Methods
def messages_to_expire(until_date)
messages = {}
$redis.zrangebyscore(eea_id, 0, days_since_epoch(until_date)).each do |message|
folder, message_id = message_parts(message)
messages[folder] ||= []
messages[folder] << message_id
end
messages
end
def days_since_epoch(date)
(date - epoch).to_i
end
def epoch
Date.new(1970,1,1)
end
def message_parts(message)
message.split("::")
end
def member_string(folder, message_id)
"#{folder}::#{message_id}"
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment