Sha256: be585ac89aee3a8e6387323f264da0e64297a9e5a91307e805321ddba18a107a

Contents?: true

Size: 873 Bytes

Versions: 5

Compression:

Stored size: 873 Bytes

Contents

require 'thread'

module Chicago
  module ETL
    # Provides a thread-safe wrapper around an incrementing number.
    #
    # Intended to be used for key builders, rather than using the
    # database's AUTO INCREMENT functionality.
    #
    # @api private
    class Counter
      # Returns the current number this counter is on.
      attr_reader :current

      # Creates a new counter, optionally with a starting count.
      def initialize(current_number=0, &block)
        @mutex = Mutex.new
        if block
          @block = block
        else
          @current = current_number || 0
        end
      end

      # Returns the next number.
      #
      # Modifies the current state of the counter.
      def next
        @current = (@block.call || 0) if @current.nil?
        @mutex.synchronize do
          @current += 1
        end
      end
    end
  end
end

Version data entries

5 entries across 5 versions & 1 rubygems

Version Path
chicago-etl-0.0.13 lib/chicago/etl/counter.rb
chicago-etl-0.0.12 lib/chicago/etl/counter.rb
chicago-etl-0.0.11 lib/chicago/etl/counter.rb
chicago-etl-0.0.10 lib/chicago/etl/counter.rb
chicago-etl-0.0.9 lib/chicago/etl/counter.rb