Skip to content

Instantly share code, notes, and snippets.

@fnando
Created November 10, 2010 02:10
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save fnando/670224 to your computer and use it in GitHub Desktop.
Save fnando/670224 to your computer and use it in GitHub Desktop.
Generate readable tokens
class Token
VOWELS = %w[a e i o u]
CONSONANTS = ("a".."z").to_a - VOWELS
NUMBERS = (0..9).to_a
def self.readable(size = 12)
String.new.tap do |s|
half = size / 2
1.upto(size) do |i|
if i == half
char = NUMBERS.sample.to_s
elsif i.odd?
char = CONSONANTS.sample
else
char = VOWELS.sample
end
s << (NUMBERS.sample.even? ? char.upcase : char)
end
end
end
end
if $0 == __FILE__
require "test/unit"
class TokenTest < Test::Unit::TestCase
def test_respect_request_size
assert_equal 4, Token.readable(4).size
assert_equal 5, Token.readable(5).size
assert_equal 6, Token.readable(6).size
assert_equal 7, Token.readable(7).size
assert_equal 8, Token.readable(8).size
end
def test_always_insert_a_number
assert_match /\d/, Token.readable(4)
assert_match /\d/, Token.readable(5)
assert_match /\d/, Token.readable(6)
assert_match /\d/, Token.readable(7)
assert_match /\d/, Token.readable(8)
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment