BigW Consortium Gitlab

uniquify.rb 645 Bytes
Newer Older
1 2 3
class Uniquify
  # Return a version of the given 'base' string that is unique
  # by appending a counter to it. Uniqueness is determined by
4
  # repeated calls to the passed block.
5 6 7
  #
  # If `base` is a function/proc, we expect that calling it with a
  # candidate counter returns a string to test/return.
8
  def string(base)
9
    @base = base
10 11
    @counter = nil

12
    increment_counter! while yield(base_string)
13
    base_string
14 15 16 17
  end

  private

18 19 20 21 22 23 24 25
  def base_string
    if @base.respond_to?(:call)
      @base.call(@counter)
    else
      "#{@base}#{@counter}"
    end
  end

26
  def increment_counter!
27 28
    @counter ||= 0
    @counter += 1
29 30
  end
end