Assigning Each User a Unique 100 character Hash in Ruby on Rails

后端 未结 3 1126
北海茫月
北海茫月 2021-02-03 12:22

I have a form on a website that takes in some personal information from the visitor. I\'m passing this information to another service and I need to assign each one of these for

相关标签:
3条回答
  • 2021-02-03 12:40

    The Ruby standard lib has a module for generating GUIDs:

    http://ruby-doc.org/stdlib/libdoc/digest/rdoc/classes/Digest/SHA2.html

    Example:

    Digest::SHA1.hexdigest(Time.now.to_s)
    
    0 讨论(0)
  • 2021-02-03 12:43
    ActiveSupport::SecureRandom.hex(50)
    

    The chance of this not being unique is astronomical.

    Alternate simple "does not scale" race condition fail solution.

    class MyModel < ActiveRecord::Base
      before_create :assign_unique_token
    
      private
    
      def assign_unique_token
        self.unique_token = ActiveSupport::SecureRandom.hex(50) until unique_token?
      end
    
      def unique_token?
        self.class.count(:conditions => {:unique_token => unique_token}) == 0
      end
    end
    

    If you really want to make sure, make an unique index on the column, and handle a DB uniqueness error by retrying, similar to my implementation above.

    0 讨论(0)
  • 2021-02-03 12:47

    If you use a Cipher you can encrypt an always different message to get an always different key:

      def encrypt(data, key, cipher_type)
        aes = OpenSSL::Cipher::Cipher.new(cipher_type)
        aes.encrypt
        aes.key = key
        aes.update(data) + aes.final      
      end
    
    >> Base64.encode64(encrypt(Time.now.to_s, "some_key_long_enough_for_the_job", "AES-256-ECB"))
    => "sKJU3qhszV30Ya9vMFvbqIXus+QygICdDyr7UQFWLeM=\n"
    
    0 讨论(0)
提交回复
热议问题