Rails plugin for generating unique links?

人走茶凉 提交于 2019-12-06 07:01:33

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!

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!