2018-04-19 05:31:01 -04:00
|
|
|
# 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-02-03 07:55:50 -05:00
|
|
|
class Uniquify
|
2018-04-19 05:31:01 -04:00
|
|
|
def initialize(counter = nil)
|
2018-04-19 02:59:37 -04:00
|
|
|
@counter = counter
|
2018-04-19 05:31:01 -04:00
|
|
|
end
|
|
|
|
|
|
|
|
def string(base)
|
|
|
|
@base = base
|
2017-02-03 07:55:50 -05:00
|
|
|
|
2017-02-16 02:05:10 -05:00
|
|
|
increment_counter! while yield(base_string)
|
2017-02-06 14:02:35 -05:00
|
|
|
base_string
|
2017-02-03 07:55:50 -05:00
|
|
|
end
|
|
|
|
|
|
|
|
private
|
|
|
|
|
2017-02-06 14:02:35 -05:00
|
|
|
def base_string
|
|
|
|
if @base.respond_to?(:call)
|
|
|
|
@base.call(@counter)
|
|
|
|
else
|
|
|
|
"#{@base}#{@counter}"
|
|
|
|
end
|
|
|
|
end
|
|
|
|
|
2017-02-03 07:55:50 -05:00
|
|
|
def increment_counter!
|
2017-02-16 02:05:10 -05:00
|
|
|
@counter ||= 0
|
|
|
|
@counter += 1
|
2017-02-03 07:55:50 -05:00
|
|
|
end
|
|
|
|
end
|