Skip to content

Instantly share code, notes, and snippets.

@schof
Created February 8, 2015 01:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save schof/2cfc8989d2a37e9a34f1 to your computer and use it in GitHub Desktop.
Save schof/2cfc8989d2a37e9a34f1 to your computer and use it in GitHub Desktop.
Order Number Generator
# Current time in hex (saves a few chars)
n = Time.now.to_i.to_s(16)
# Add some more random digits and convert to base24 (more entropy w/minimal chars)
n += rand(9999).to_s(24)
# Make sure the whole thing is exactly 10 chars
n.ljust(10).gsub(" ", "0")
# Convert to upcase
n.upcase
@phstc
Copy link

phstc commented Feb 8, 2015

👍

Really liked the usage of hex and base64!

def generate_order_id
  # Current time in hex (saves a few chars)
  n = Time.now.to_i.to_s(16)

  # Add some more random digits and convert to base24 (more entropy w/minimal chars)
  n += rand(9999).to_s(24)

  # Make sure the whole thing is exactly 10 chars
  n.ljust(10).gsub(' ') { rand(9) }

  # Convert to upcase
  n.upcase
end

def order_id_to_time(order_id)
  Time.at(order_id[0..7].hex)
end

order_id = generate_order_id

puts order_id
# => 54D77687C86

puts order_id_to_time(order_id)
# => 2015-02-08 12:45:27 -0200

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment