问题
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.
回答1:
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:
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.
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!
来源:https://stackoverflow.com/questions/2521904/rails-plugin-for-generating-unique-links