Last active
October 11, 2025 21:37
-
-
Save vmsp/8c1f36b91175895cf3a9837868ec321b to your computer and use it in GitHub Desktop.
Nano ID for Ruby
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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 |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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