diff options
author | GitLab Bot <gitlab-bot@gitlab.com> | 2023-02-20 15:12:47 +0300 |
---|---|---|
committer | GitLab Bot <gitlab-bot@gitlab.com> | 2023-02-20 15:12:47 +0300 |
commit | c984b0faf409dbe91a7998260fe4b8299cf21ad4 (patch) | |
tree | b1e434732c9d94ecaab0727f56a811b80a61a371 /lib/gitlab/utils | |
parent | bd28d0fa02dc73794e013159512900f8d10fa10b (diff) |
Add latest changes from gitlab-org/gitlab@master
Diffstat (limited to 'lib/gitlab/utils')
-rw-r--r-- | lib/gitlab/utils/uniquify.rb | 45 |
1 files changed, 45 insertions, 0 deletions
diff --git a/lib/gitlab/utils/uniquify.rb b/lib/gitlab/utils/uniquify.rb new file mode 100644 index 00000000000..b5908d18103 --- /dev/null +++ b/lib/gitlab/utils/uniquify.rb @@ -0,0 +1,45 @@ +# frozen_string_literal: true + +# 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. + +module Gitlab + module Utils + class Uniquify + def initialize(counter = nil) + @counter = counter + end + + 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 + end +end |