使用uuidtools在Rails中生成一个简短的UUID字符串

时间:2013-01-07 12:46:03

标签: ruby ruby-on-rails-3 uuid

我必须生成一个唯一的随机字符串,该字符串将存储在数据库中。为此,我使用了“uuidtools”宝石。然后在我的控制器中添加了以下行:

require "uuidtools"

然后在我的控制器中创建方法我声明了一个'temp'变量并生成一个独特的随机'uuid'字符串,如下所示:

temp=UUIDTools::UUID.random_create

正在创建一个像这样的字符串:

f58b1019-77b0-4d44-a389-b402bb3e6d50

现在我的问题是我必须缩短它,最好在8-10个字符之内。现在我该怎么办?是否可以传递任何参数使其成为理想的长度字符串?

提前致谢...

2 个答案:

答案 0 :(得分:38)

你不需要uuidtools。您可以使用Secure Random

[1] pry(main)> require "securerandom"
=> true
[2] pry(main)> SecureRandom.hex(20)
=> "82db4d707c4c5db3ebfc349da09c991b7ca0faa1"
[3] pry(main)> SecureRandom.base64(20)
=> "CECjUqNvPBaq0o4OuPy8RvsEoCY="

45传递给hex将分别生成8个和10个字符的十六进制字符串。

[5] pry(main)> SecureRandom.hex(4)
=> "a937ec91"
[6] pry(main)> SecureRandom.hex(5)
=> "98605bb20a"

答案 1 :(得分:3)

请详细了解我最近如何在我的项目中使用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也很有用。

请告诉我如果您在使用过程中遇到任何问题,那么简单!