Skip to content

Instantly share code, notes, and snippets.

@kke
Created April 3, 2012 10:14
Show Gist options
  • Select an option

  • Save kke/2290846 to your computer and use it in GitHub Desktop.

Select an option

Save kke/2290846 to your computer and use it in GitHub Desktop.
super id
require 'socket' # for gethostname
class LogId
@@hostname = Socket.gethostname
@@hostid = @@hostname.gsub('.', '').downcase.each_char.inject(""){|r,c| r += c.ord.to_s}.to_i
@@hostid_short = @@hostname.gsub('.', '').downcase.each_char.inject(0){|r,c| r += c.ord}
def self.get(*opts)
# opts = [:host] if opts.empty? # modify defaults
time = Time.now.usec.to_i
"#{opts.include?(:host) ? "#{opts.include?(:plain) ? @@hostname : base62(opts.include?(:long) ? @@hostid : @@hostid_short)}-" : ''}#{base62(Time.now.to_i)}-#{base62(Time.now.nsec.to_i)}#{opts.include?(:random) ? "-#{base62(rand(1024))}" : ''}"
end
private
def self.base62(num)
base62 = ('0'..'9').to_a + ('a'..'z').to_a + ('A'..'Z').to_a
s = ''
while num > 0
s << base62[num.modulo(62)]
num /= 62
end
s.reverse
end
end
puts LogId.get(:host, :long, :random)
# output of get(:host, :random) :
# 8P-1sf0Rl-ogYlW-86
# ^ host-id
# ^ unixtime
# ^ nanoseconds
# ^ random(1024)
# $ ruby super-id.rb
# get() 1sf0Rl-ofGQH
# get(:random) 1sf0Rl-og4n8-6k
# get(:host, :long) 32AjoHXL-1sf0Rl-ogB5T
# get(:host, :long, :random) 32AjoHXL-1sf0Rl-ogYlW-86
# get(:host, :plain, :random) maventa110-1sf0Rl-ohkPh-6i
# get(:host, :random) 8P-1sf0Rl-ohH6B-52
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment