UUID in Ruby 1.8

From SoftOver
Jump to: navigation, search

Ruby 1.9 added couple useful methods to SecureRandom - uuid and urlsafe_base64. Here is a simple backport (copy-paste, documentation omitted for the sake of simplicity) to 1.8

require 'securerandom'
# Backport of missing SecureRandom methods from 1.9

module SecureRandom
  class << self
    def method_missing(method_sym, *arguments, &block)
      case method_sym
      when :urlsafe_base64
        r19_urlsafe_base64(*arguments)
      when :uuid
        r19_uuid(*arguments)
      else
        super
      end
    end
    
    private
    def r19_urlsafe_base64(n=nil, padding=false)
      s = [random_bytes(n)].pack("m*")
      s.delete!("\n")
      s.tr!("+/", "-_")
      s.delete!("=") if !padding
      s
    end

    def r19_uuid
      ary = random_bytes(16).unpack("NnnnnN")
      ary[2] = (ary[2] & 0x0fff) | 0x4000
      ary[3] = (ary[3] & 0x3fff) | 0x8000
      "%08x-%04x-%04x-%04x-%04x%08x" % ary
    end
  end
end
SecureRandom.urlsafe_base64
=> "NvVzvkDJ6gGhlQwvNxJKHg"

SecureRandom.urlsafe_base64(16, true)
=> "32oojSK89BDp2i-MpeE61w=="

SecureRandom.uuid
=> "cdb9eef5-7a5a-4eab-9783-51182ac6a722"
Personal tools
Namespaces

Variants
Actions
Navigation
Tools