3

I want to create a web app similar to http://www.pastebin.com/ in Ruby on Rails. pastebin.com uses a random string to identify an item. Ruby on Rails uses an auto-incrementing number. How can I make Ruby on Rails also use these random strings as IDs for items, instead of auto-incrementing numbers?

Thanks

edgerunner
  • 14,873
  • 2
  • 57
  • 69
  • Possible dupe: http://stackoverflow.com/questions/831746/how-to-make-model-ids-in-rails-unpredictable-and-random – jhleath Jul 02 '10 at 12:54
  • Is there a reason you can't use auto-inc as a identifier and the random string as a filter? – Fossmo Feb 21 '11 at 07:53

4 Answers4

7

Use a guaranteed random string generator, base64 encode it and then shorten it to something acceptable (8 characters?)

require 'uuidtools'
require 'base64'
uid = UUIDTools::UUID.random_create
Base64.encode64(uid)[0..7]
=> "Y2I2ZTQ5"

In Rails you would alter your routes to load based on a :slug column, and set this value using something like this:

before_create do
  self.slug = Base64.encode64(UUIDTools::UUID.random_create)[0..8]
end
stef
  • 14,172
  • 2
  • 48
  • 70
2

For vanilla ruby

require 'securerandom'
require 'base64'

slug = Base64.encode64(SecureRandom.uuid)[0..10]
=> "YWVkNzZmYjI" 
=> "MzQxMDkxY2U"
cevaris
  • 5,671
  • 2
  • 49
  • 34
2

I believe you can override the implementation of to_param in the models of interest. There's a fuller explanation of the technique here

bjg
  • 7,457
  • 1
  • 25
  • 21
0

generate a random string as key and put it into a db table? make sure the key is uniq?

base="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890"
(0...10).map{base[rand(base.length)]}.join
c2h2
  • 11,911
  • 13
  • 48
  • 60