2017-02-03 07:55:50 -05:00
|
|
|
class Uniquify
|
|
|
|
# Return a version of the given 'base' string that is unique
|
|
|
|
# by appending a counter to it. Uniqueness is determined by
|
2017-02-16 02:05:10 -05:00
|
|
|
# repeated calls to the passed block.
|
2017-02-03 07:55:50 -05:00
|
|
|
#
|
|
|
|
# If `base` is a function/proc, we expect that calling it with a
|
|
|
|
# candidate counter returns a string to test/return.
|
2017-02-16 02:05:10 -05:00
|
|
|
def string(base)
|
2017-02-06 14:02:35 -05:00
|
|
|
@base = base
|
2017-02-03 07:55:50 -05:00
|
|
|
@counter = nil
|
|
|
|
|
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
|