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 n
I believe you can override the implementation of to_param in the models of interest. There's a fuller explanation of the technique here
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
For vanilla ruby
require 'securerandom'
require 'base64'
slug = Base64.encode64(SecureRandom.uuid)[0..10]
=> "YWVkNzZmYjI"
=> "MzQxMDkxY2U"
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