Welcome to mirror list, hosted at ThFree Co, Russian Federation.

uniquify.rb « concerns « models « app - gitlab.com/gitlab-org/gitlab-foss.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: db51ed2dbebe73a62d106a8ba3ac6f779d6604bc (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
class Uniquify
  # Return a version of the given 'base' string that is unique
  # by appending a counter to it. Uniqueness is determined by
  # repeated calls to the passed block.
  #
  # You can pass an initial value for the counter, if not given
  # counting starts from 1.
  #
  # If `base` is a function/proc, we expect that calling it with a
  # candidate counter returns a string to test/return.
  def string(base, counter = nil)
    @base = base
    @counter = counter

    increment_counter! while yield(base_string)
    base_string
  end

  private

  def base_string
    if @base.respond_to?(:call)
      @base.call(@counter)
    else
      "#{@base}#{@counter}"
    end
  end

  def increment_counter!
    @counter ||= 0
    @counter += 1
  end
end