使用uuidtools在Rails中生成一个简短的UUID字符串
我必须生成一个唯一的随机字符串,该字符串将存储在数据库中。 为此,我使用了“uuidtools”gem。 然后在我的控制器中添加了以下行:
require "uuidtools"
然后在我的控制器创建方法我已经声明了一个’temp’变量并生成一个独特的随机’uuid’字符串,如下所示:
temp=UUIDTools::UUID.random_create
这是创建一个像这样的字符串:
f58b1019-77b0-4d44-a389-b402bb3e6d50
现在我的问题是我必须缩短它,最好在8-10个字符之内。 现在我该怎么办? 是否可以传递任何参数使其成为一个理想的长度字符串?
提前致谢…
你不需要uuidtools。 您可以使用安全随机 。
[1] pry(main)> require "securerandom" => true [2] pry(main)> SecureRandom.hex(20) => "82db4d707c4c5db3ebfc349da09c991b7ca0faa1" [3] pry(main)> SecureRandom.base64(20) => "CECjUqNvPBaq0o4OuPy8RvsEoCY="
将4
和5
传递给hex
将分别生成8和10个字符的hex字符串。
[5] pry(main)> SecureRandom.hex(4) => "a937ec91" [6] pry(main)> SecureRandom.hex(5) => "98605bb20a"
请详细了解我最近在我的一个项目中如何使用securerandom,绝对可以帮到你!
在你的lib / usesguid.rb中创建usesguid.rb文件并粘贴下面的代码 –
require 'securerandom' module ActiveRecord module Usesguid #:nodoc: def self.append_features(base) super base.extend(ClassMethods) end module ClassMethods def usesguid(options = {}) class_eval do self.primary_key = options[:column] if options[:column] after_initialize :create_id def create_id self.id ||= SecureRandom.uuid end end end end end end ActiveRecord::Base.class_eval do include ActiveRecord::Usesguid end
在config / application.rb中添加以下行来加载文件 –
require File.dirname(__FILE__) + '/../lib/usesguid'
为UUID函数创建迁移脚本,如下所述 –
class CreateUuidFunction < ActiveRecord::Migration def self.up execute "create or replace function uuid() returns uuid as 'uuid-ossp', 'uuid_generate_v1' volatile strict language C;" end def self.down execute "drop function uuid();" end end
以下是联系人迁移的示例,我们如何使用它 -
class CreateContacts < ActiveRecord::Migration def change create_table :contacts, id: false do |t| t.column :id, :uuid, null:false t.string :name t.string :mobile_no t.timestamps end end end
最后如何使用到您的模型中
class Contact < ActiveRecord::Base usesguid end
这将帮助您为rails应用程序配置UUID。
这对于Rails 3.0,3.1,3.2和4.0也很有用。
请告诉我如果您在使用过程中遇到任何问题,那么简单!