views:

60

answers:

1

There are many places in my application where I need to generate links with unique tokens (foo.com/g6Ce7sDygw or whatever). Each link may be associated with some session data and would take the user to some specific controller/action.

Does anyone know of a gem/plugin that does this? It's easy enough to implement, but would be cleaner without having to write it from scratch for each app.

A: 

I needed the same think, you need and I implemented it by myself. I don't know about any plugin that does what you want. As you wrote, implementing it is not so difficult. Here is my solution:

  1. Since I didn't want to use UUID (because it is coded with hex). I wanted some random alphanumeric with big and small letters. I added this method to String class:

    def String.random_alphanumeric(size=20)
      s = ""
     size.times { s << (i = Kernel.rand(62); i += ((i < 10) ? 48 : ((i < 36) ? 55 : 61 ))).chr }
      s
    end
    

    With it you can create uniqe link with:

    link = String.random_alphanumeric
    

    As a parameter you can set size of desired string.

  2. Another important thing is searching for this string in db. I use mysql and by default it isn't case sensitive, so I added search method to my UniqueLink model:

    def self.find_uid(search_for)
      find_by_sql("SELECT * FROM workshop_application_unique_ids where uid = '#{search_for}' COLLATE utf8_bin ORDER BY created_at DESC").first
    end
    

Hope it helps!

klew
Nice. More "compact" by using more different characters.
Allan Grant
How's this simpler than using uuidtools?
Marcos Placona
@mplacona: I don't know if it is simpler or more complicated than with uuid. It's different. For me it is better because I wanted to use characters: a-z A-Z 0-9, not only hexadecimal numbers as it is in uuid. Since in question there was example `foo.com/g6Ce7sDygw` I thought it would be better than uuid. Adding this `random_alphanumeric` method is as simple as installing another gem.
klew