Created
August 20, 2016 04:37
-
-
Save djpate/b3129eea357a0aaf1ecd7cdca813fe83 to your computer and use it in GitHub Desktop.
Unique views store in redis with daily rotation
This file contains 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
class RedisViewCounter | |
attr_reader :object | |
def initialize(object) | |
@object = object | |
end | |
def register_view(fingerprint) | |
created = !$redis.exists(daily_key) | |
if $redis.sadd(daily_key, fingerprint) | |
$redis.incr count_key | |
end | |
$redis.expire(daily_key, Time.now.seconds_until_end_of_day) if created | |
end | |
def count | |
$redis.get(count_key).to_i | |
end | |
private | |
def count_key | |
"view_count_#{object.class.name}_#{object.id}" | |
end | |
def daily_key | |
"daily_views_#{object.class.name}_#{object.id}_#{Date.today}".underscore | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment