Skip to content

Instantly share code, notes, and snippets.

@djpate
Created August 20, 2016 04:37
Show Gist options
  • Save djpate/b3129eea357a0aaf1ecd7cdca813fe83 to your computer and use it in GitHub Desktop.
Save djpate/b3129eea357a0aaf1ecd7cdca813fe83 to your computer and use it in GitHub Desktop.
Unique views store in redis with daily rotation
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