Generating Guids in Ruby

后端 未结 10 1700
南笙
南笙 2020-11-27 10:53

I have problem that is really easily solved with Guids.

In particular, for a password reset workflow, I would like to send a Guid token to a user\'s email and have

相关标签:
10条回答
  • 2020-11-27 11:25

    We use UUIDTools and have no problems with it.

    0 讨论(0)
  • 2020-11-27 11:28

    Did you look at UUIDTools?

    UUIDTools was designed to be a simple library for generating any of the various types of UUIDs (or GUIDs if you prefer to call them that). It conforms to RFC 4122 whenever possible.

    0 讨论(0)
  • 2020-11-27 11:30

    As of Ruby 1.9, uuid generation is built-in. Use the SecureRandom.uuid function.

    For example:

    require 'securerandom'
    SecureRandom.uuid # => "96b0a57c-d9ae-453f-b56f-3b154eb10cda"
    
    0 讨论(0)
  • 2020-11-27 11:30

    While programming late at night I came up with the following solution (based off Simone's) for generating a unique GUID in Rails. I am not proud of it but it does work quite well.

    while Order.find_by_guid(guid = rand(36**8).to_s(36).upcase).present?; end
    
    0 讨论(0)
  • 2020-11-27 11:30

    This is a neet technique I learnt from JavaScript:

    def uuid
        "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx".gsub("x") do
            "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"[rand(36)]
        end
    end
    

    Although in a more 'ruby way' one could also do:

    def uuid
        "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx".gsub("x") do
            rand(16).to_s(16)
        end
    end
    
    0 讨论(0)
  • 2020-11-27 11:32

    When I used uuid gems recommended in this question, no one can generate unique and random UUID. My answer is a work around, if we have gem later to satisfy the request, you'd better to use gem in Ruby.

    I try most recommended uuid gems in this question, but no one make me satisfied, we need unique and random uuid. I directly run system command uuidgen in ruby, and I like the result, and share here.

    puts `uuidgen`
    8adea17d-b918-43e0-b82f-f81b3029f688
    puts `uuidgen`
    6a4adcce-8f64-41eb-bd7e-e65ee6d11231
    puts `uuidgen`
    51d5348b-8fc3-4c44-a6f7-9a8588d7f08a
    puts `uuidgen`
    332a0fa3-7b07-41e1-9fc8-ef804a377e4e
    

    if compare with uuid gem, you will know the difference.

    irb(main):003:0> uuid.generate
    => "40cdf890-ebf5-0132-2250-20c9d088be77"
    irb(main):004:0> uuid.generate
    => "4161ac40-ebf5-0132-2250-20c9d088be77"
    

    Test environment is linux and Mac OS environment.

    0 讨论(0)
提交回复
热议问题