Skip to content

Instantly share code, notes, and snippets.

@vmsp
Last active October 11, 2025 21:37
Show Gist options
  • Select an option

  • Save vmsp/8c1f36b91175895cf3a9837868ec321b to your computer and use it in GitHub Desktop.

Select an option

Save vmsp/8c1f36b91175895cf3a9837868ec321b to your computer and use it in GitHub Desktop.
Nano ID for Ruby
module PublicID
# https://planetscale.com/blog/why-we-chose-nanoids-for-planetscales-api
extend ActiveSupport::Concern
included do
before_create :set_pid
end
PUBLIC_ID_MAX_RETRIES = 1000
private
def set_pid
return if pid.present?
PUBLIC_ID_MAX_RETRIES.times do
self.pid = NanoID.generate
return unless self.class.exists?(pid: pid)
end
raise "Failed to generate a unique pid"
end
end
module NanoID
# https://github.com/ai/nanoid/blob/main/index.js
extend self
URL_ALPHABET = "useandom-26T198340PX75pxJACKVERYMINDBUSHWOLF_GQZbfghjklqvwyzrict"
def generate(size = 21)
bytes = SecureRandom.bytes(size).bytes
id = +""
bytes.each { |c| id << URL_ALPHABET[c & 63] }
id
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment