Sha256: ec3a9e169003f6809ed3e060831b5a492a3136f8ef6d3d31cafe6fec8f828aa0

Contents?: true

Size: 981 Bytes

Versions: 1

Compression:

Stored size: 981 Bytes

Contents

require "digest/sha1"
require "socket"

class PropertybaseId
  class Generator
    def initialize
      @counter = 0
      @mutex = Mutex.new
    end

    def generate(object: )
      @mutex.synchronize do
        PropertybaseId.new(
          object_id: pb_object_id(object),
          host_id: host_id,
          time: ::Time.now.to_i,
          process_id: process_id,
          counter: next_counter
        )
      end
    end

    private

    def pb_object_id(object)
      PropertybaseId::Mappings.objects.fetch(object) do
        raise ArgumentError, "Object #{object.inspect} not found"
      end
    end

    def host_id
      @_host_id ||= Digest::SHA1.hexdigest(Socket.gethostname).to_i(16) % max_value(2)
    end

    def next_counter
      @counter = (@counter + 1) % max_value(5)
    end

    def process_id
      "#{Process.pid}#{Thread.current.object_id}".hash % max_value(2)
    end

    def max_value(digits)
      ("z" * digits).to_i(36) + 1
    end
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
propertybase_id-0.3.0 lib/propertybase_id/generator.rb