debian-mirror-gitlab/app/models/concerns/uniquify.rb

Ignoring revisions in .git-blame-ignore-revs. Click here to bypass and see the normal blame view.

41 lines
810 B
Ruby
Raw Normal View History

2018-11-20 20:47:30 +05:30
# frozen_string_literal: true
2018-10-15 14:42:47 +05:30
# 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.
2017-08-17 22:00:37 +05:30
class Uniquify
2018-10-15 14:42:47 +05:30
def initialize(counter = nil)
@counter = counter
end
2017-08-17 22:00:37 +05:30
def string(base)
@base = base
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