Skip to content

Commit 4a31a5a

Browse files
committed
✨ add helper function to generate random identifier
Foreign key constraints name will include 10 character long random identifier if not specified. ref: https://api.rubyonrails.org/v4.2.0/classes/ActiveRecord/ConnectionAdapters/SchemaStatements.html#method-i-add_foreign_key The original implementation returns 10 character long random HEX string (e.g. "c5b6f2d87a", "4e2f7ab9c1", ...) ref: https://github.com/rails/rails/blob/77fe87cccd90859e67c958cbf63d7e5662174fd8/activerecord/lib/active_record/connection_adapters/abstract/schema_statements.rb#L984-L988
1 parent 8d71055 commit 4a31a5a

File tree

2 files changed

+24
-0
lines changed

2 files changed

+24
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
import { describe, expect, it } from 'vitest'
2+
import { generateRandomIdentifier } from './generateRandomIdentifier.js'
3+
4+
describe('generateRandomIdentifier', () => {
5+
it('should generate random identifier with given length', () => {
6+
expect(generateRandomIdentifier(4)).toHaveLength(4)
7+
expect(generateRandomIdentifier(10)).toHaveLength(10)
8+
})
9+
10+
it('should only contain alphanumeric characters', () => {
11+
expect(/^[a-f0-9]+$/.test(generateRandomIdentifier(100))).toBe(true)
12+
})
13+
14+
it('should return different values on multiple calls', () => {
15+
// A collision is possible, though the probability is extremely low (16^{-10}, roughly 1 in 1,000,000,000)
16+
const result1 = generateRandomIdentifier(10)
17+
const result2 = generateRandomIdentifier(10)
18+
expect(result1).not.toBe(result2)
19+
})
20+
})
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,4 @@
1+
export const generateRandomIdentifier = (length: number) =>
2+
Array.from({ length }, () =>
3+
'0123456789abcdef'.charAt(Math.floor(Math.random() * 16)),
4+
).join('')

0 commit comments

Comments
 (0)