用于生成唯一链接的 Rails 插件? [英] Rails plugin for generating unique links?

查看:45
本文介绍了用于生成唯一链接的 Rails 插件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的应用程序中有很多地方需要生成带有唯一标记的链接(foo.com/g6Ce7sDygw 或其他).每个链接都可能与一些会话数据相关联,并将用户带到某个特定的控制器/操作.

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.

推荐答案

我需要同样的想法,你需要,我自己实现了.我不知道有什么插件可以做你想要的.正如你所写的,实现它并不是那么困难.这是我的解决方案:

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. 因为我不想使用 UUID(因为它是用十六进制编码的).我想要一些带有大写和小写字母的随机字母数字.我将此方法添加到 String 类:

  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.

另一个重要的事情是在 db 中搜索这个字符串.我使用 mysql,默认情况下它不区分大小写,所以我在 UniqueLink 模型中添加了搜索方法:

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

希望有帮助!

这篇关于用于生成唯一链接的 Rails 插件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆