Sha256: 5de8245aa5fb5de2abf68a0cb06b3cf0d4dcd47ece105a5fbc6a4196fe4dc38a

Contents?: true

Size: 1.66 KB

Versions: 16

Compression:

Stored size: 1.66 KB

Contents

require 'delegate'
require 'securerandom'

def SecureRandom.format_uuid hex32
  hex32.sub(
    @@format_pattern ||= /(........)(....)(....)(....)(............)/,
    @@format_string ||= '\1-\2-\3-\4-\5'
  )
end

unless defined? SecureRandom.uuid
  # I think this only applies to 1.8.6 (and JRuby/Rubinius in 1.8 mode) now:
  def SecureRandom.uuid
    format_uuid(hex(16))
  end
end

# The Guid class is what it says on the packet, but you can assert a :new one.
class Guid
  SEQ_FILE_NAME = "/tmp/ActiveFactsRandom"
  @@sequence = nil
  def initialize(i = :new)
    @@sequence = ENV['ACTIVEFACTS_RANDOM'] || false if @@sequence == nil
    if i == :new
      case @@sequence
      when 'fixed'
	@@counter ||= 0
	@value = SecureRandom.format_uuid('%032x' % (@@counter += 1))
      when 'record'
	@@sequence_file ||= File.open(SEQ_FILE_NAME, 'w')
	@value = SecureRandom.uuid.freeze
	@@sequence_file.puts(@value)
      when 'replay'
	@@sequence_file ||= File.open(SEQ_FILE_NAME, 'r')
	@value = @@sequence_file.gets.chomp
      else
	@value = SecureRandom.uuid.freeze
      end
    elsif (v = i.to_s).length == 36 and !(v !~ /[^0-9a-f]/i)
      @value = v.clone.freeze
    else
      raise ArgumentError.new("Illegal non-Guid value #{i.inspect} given for Guid")
    end
  end

  def to_s
    @value
  end

  # if the value is unassigned, it equal?(:new).
  def equal? value
    @value == value
  end

  def == value
    @value == value.to_s
  end

  def inspect
    "\#<Guid #{@value}>"
  end

  def hash                              #:nodoc:
    @value.hash
  end

  def eql?(o)                           #:nodoc:
    to_s.eql?(o.to_s)
  end

  def <=>(o)				#:nodoc:
    to_s.<=>(o.to_s)
  end

end

Version data entries

16 entries across 16 versions & 1 rubygems

Version Path
activefacts-api-1.9.5 lib/activefacts/api/guid.rb
activefacts-api-1.9.4 lib/activefacts/api/guid.rb
activefacts-api-1.9.2 lib/activefacts/api/guid.rb
activefacts-api-1.9.0 lib/activefacts/api/guid.rb
activefacts-api-1.8.5 lib/activefacts/api/guid.rb
activefacts-api-1.8.4 lib/activefacts/api/guid.rb
activefacts-api-1.8.3 lib/activefacts/api/guid.rb
activefacts-api-1.8.1 lib/activefacts/api/guid.rb
activefacts-api-1.8.0 lib/activefacts/api/guid.rb
activefacts-api-1.7.1 lib/activefacts/api/guid.rb
activefacts-api-1.7.0 lib/activefacts/api/guid.rb
activefacts-api-1.6.0 lib/activefacts/api/guid.rb
activefacts-api-1.5.0 lib/activefacts/api/guid.rb
activefacts-api-1.4.0 lib/activefacts/api/guid.rb
activefacts-api-1.3.1 lib/activefacts/api/guid.rb
activefacts-api-1.3.0 lib/activefacts/api/guid.rb