Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 4 additions & 5 deletions lib/join_code_generator.rb
Original file line number Diff line number Diff line change
@@ -1,19 +1,18 @@
# frozen_string_literal: true

require 'securerandom'

class JoinCodeGenerator
# Omit K, X, Z — commonly confused or offensive in short codes.
CONSONANTS = %w[B C D F G H J L M N P Q R S T V W Y].freeze

# Format: CDDD-CDDD (e.g., B123-C456). C = consonant from CONSONANTS, D = digit.
FORMAT_REGEX = Regexp.new("\\A(?:#{CONSONANTS.join('|')})\\d{3}-(?:#{CONSONANTS.join('|')})\\d{3}\\z").freeze

cattr_accessor :random

self.random ||= Random.new

def self.generate
seg = lambda do
"#{CONSONANTS.sample(random: random)}#{format('%03d', random.rand(1000))}"
consonant = CONSONANTS[SecureRandom.random_number(CONSONANTS.length)]
"#{consonant}#{format('%03d', SecureRandom.random_number(1000))}"
end

"#{seg.call}-#{seg.call}"
Expand Down
9 changes: 9 additions & 0 deletions spec/lib/join_code_generator_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,15 @@
it 'matches CDDD-CDDD' do
expect(described_class.generate).to match(described_class::FORMAT_REGEX)
end

it 'uses SecureRandom for each code component' do
allow(SecureRandom).to receive(:random_number).with(described_class::CONSONANTS.length).and_return(0, 1)
allow(SecureRandom).to receive(:random_number).with(1000).and_return(123, 456)

expect(described_class.generate).to eq('B123-C456')
expect(SecureRandom).to have_received(:random_number).with(described_class::CONSONANTS.length).twice
expect(SecureRandom).to have_received(:random_number).with(1000).twice
end
end

describe '.normalize' do
Expand Down
Loading