Last active
May 12, 2016 23:29
-
-
Save chsh/d2bf74996dce639b659daeb476be63e1 to your computer and use it in GitHub Desktop.
Generate periodically unique token.
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
require 'digest/sha2' | |
# usage: | |
# PeriodicalToken.generate(:min) # -> returns unique token in a minute. | |
# | |
class PeriodicalToken | |
SALT = 'RANDOMLLY-GENERATED-STRING' | |
RANGE_TO_DIV = { | |
min: 60, | |
min5: 60 * 5, | |
min15: 60 * 15, | |
min30: 60 * 30, | |
hour: 60 * 60, | |
hour3: 60 * 60 * 3, | |
hour6: 60 * 60 * 6, | |
hour12: 60 * 60 * 12, | |
day: 60 * 60 * 24, | |
week: 60 * 60 * 24 * 7 | |
} | |
def self.generate(range = :day) | |
value = format_by_range(range) | |
Digest::MD5.hexdigest(value + SALT) | |
end | |
private | |
def self.format_by_range(range) | |
range = range.to_sym | |
now = UTC.now.to_i | |
mod = now % RANGE_TO_DIV[range] | |
(now - mod).to_s | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment