Rails plugin for generating unique links?

拈花ヽ惹草 提交于 2020-01-02 12:01:40

问题


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:

  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!



来源:https://stackoverflow.com/questions/2521904/rails-plugin-for-generating-unique-links

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