Sha256: a1b1c403aeba8356a7470eee0d2e35286bef0563597c4e36d76cd9831485b8e0

Contents?: true

Size: 878 Bytes

Versions: 1

Compression:

Stored size: 878 Bytes

Contents

require "digest/sha1"

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

    def generate(object: )
      @mutex.lock
      begin
        count = next_counter
      ensure
        @mutex.unlock rescue nil
      end

      PropertybaseId.new(
        object: object,
        host_id: host_id,
        time: time,
        process_id: process_id,
        counter: count
      )
    end

    private

    def time
      @_time ||= ::Time.now.to_i
    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(3)
    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.2.0 lib/propertybase_id/generator.rb