This repository has been archived by the owner on Nov 14, 2017. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 28
/
Copy pathtiny.rb
88 lines (80 loc) · 2.23 KB
/
tiny.rb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
#
# Tiny
#
# A reversible base62 ID obfuscater
#
# Authors:
# Jacob DeHart (original PHP version) and Kyle Bragger (Ruby port)
#
# Usage:
# obfuscated_id = Tiny::tiny(123)
# original_id = Tiny::untiny(obfuscated_id)
#
# Configuration:
# * You must run Tiny::generate_set() from console to generate your TINY_SET
# Do *not* change this once you start using Tiny, as you won't be able to untiny()
# any values tiny()'ed with another set.
# * generate_set() will also print a value for TINY_EPOCH; once set, this shouldn't be
# changed either.
#
module Tiny
TINY_SET = "__put the set output by generate_set() here__"
TINY_EPOCH = 0
class << self
def tiny(id)
hex_n = ''
id = id.to_i.abs.floor
radix = TINY_SET.length
while true
r = id % radix
hex_n = TINY_SET[r,1] + hex_n
id = (id - r) / radix
break if id == 0
end
return hex_n
end
def untiny(str)
radix = TINY_SET.length
strlen = str.length
n = 0
(0..strlen - 1).each do |i|
n += TINY_SET.index(str[i,1]) * (radix ** (strlen - i - 1))
end
return n.to_s
end
# Same as tiny() but use the current UNIX timestamp - TINY_EPOCH (hat tip: Nir Yariv)
def tiny_from_timestamp
tiny(Time.now.to_f - TINY_EPOCH)
end
def generate_set
base_set = ("a".."z").to_a + ("A".."Z").to_a + (0..9).to_a
base_set = base_set.sort_by{ rand }
puts "generate_set()"
puts base_set.join('')
puts "TINY_EPOCH = #{Time.now.to_i}"
end
end
end
# Test
Tiny::generate_set
puts Tiny::tiny(-12345)
puts Tiny::tiny(12345)
puts Tiny::tiny(64)
puts Tiny::tiny(1)
puts Tiny::tiny(0)
puts Tiny::untiny(Tiny::tiny(-12345))
puts Tiny::untiny(Tiny::tiny(12345))
puts Tiny::untiny(Tiny::tiny(64))
puts Tiny::untiny(Tiny::tiny(1))
puts Tiny::untiny(Tiny::tiny(0))
time_now = Time.now.to_i
tiny_time = Tiny::tiny(time_now)
puts "#{time_now} -> #{tiny_time} -> #{Tiny::untiny(tiny_time)}"
puts Tiny::tiny_from_timestamp
puts Tiny::tiny_from_timestamp
puts Tiny::tiny_from_timestamp
puts Tiny::tiny_from_timestamp
puts Tiny::tiny_from_timestamp
puts Tiny::tiny_from_timestamp
puts Tiny::tiny_from_timestamp
puts Tiny::tiny_from_timestamp