lib/writer/overwrite_prevention.rb in writer-0.1.0 vs lib/writer/overwrite_prevention.rb in writer-0.1.1
- old
+ new
@@ -1,25 +1,61 @@
module Writer
class OverwritePrevention
- def self.adjust(name)
- count = 1
+ class << self
+ def adjust(filename)
+ name = fix_standard(filename)
+ name ||= fix_no_extension(filename)
+ name ||= fix_no_base(filename)
+ name ||= fix_no_dots(filename)
+ name
+ end
- while File.exists?(name)
- name = append_count(name, count +=1)
+ def fix_standard(name)
+ if /.+\..+/ =~ name
+ parts = name.split('.')
+ basename = parts[0..-2].join('.')
+ extension = parts.last
+
+ fix_name(name, basename, extension)
+ end
end
- name
- end
+ def fix_no_extension(name)
+ if /\.$/ =~ name
+ basename = name.gsub('.', '')
- def self.append_count(name, count)
- if (split = name.split('.')).length > 1
- ext = split.last
- split.delete(ext)
- name = split.join('.')
+ fix_name(name, basename)
+ end
end
- name = name.gsub(/--\d$/,'')
+ def fix_no_base(name)
+ if /^\./ =~ name
+ fix_name(name)
+ end
+ end
- [name + "--#{count}", '.', ext].join
+ def fix_no_dots(name)
+ unless name.include?('.')
+ fix_name(name)
+ end
+ end
+
+ private
+ def fix_name(name, base = nil, ext = nil)
+ to_fix = base || name
+ count = 1
+
+ while File.exists?(name)
+ name = append_count(to_fix, count += 1)
+ name << ".#{ext}" if base
+ end
+
+ name
+ end
+
+ def append_count(name, count)
+ name = name.gsub(/--\d*$/, '')
+ [name, "--", count].join
+ end
end
end
end