Class: Renamr::ExistenceAction

Inherits:
Action
  • Object
show all
Defined in:
lib/renamr/existence.rb

Overview

Adds number from 0 to 9 in case of file existence.

Constant Summary collapse

ITERATION =
10

Instance Method Summary collapse

Methods inherited from Action

#p2m

Constructor Details

#initialize(dir, lim) ⇒ ExistenceAction

Returns a new instance of ExistenceAction.



13
14
15
16
17
18
19
# File 'lib/renamr/existence.rb', line 13

def initialize(dir, lim)
  raise 'dir cannot be nil.' if dir.nil?
  raise 'lim cannot be nil.' if lim.nil?

  @dir = dir
  @lim = lim
end

Instance Method Details

#do(src) ⇒ Object

rubocop:disable MethodLength, CyclomaticComplexity, AbcSize



21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
# File 'lib/renamr/existence.rb', line 21

def do(src) # rubocop:disable MethodLength, CyclomaticComplexity, AbcSize
  raise 'ExistenceAction needs original file name.' if @src.nil?
  return src if src == @src
  return src unless File.exist?(File.join(@dir, src))

  if src.length == @lim
    ext = File.extname(src)
    src = src[0..@lim - ext.length - ITERATION.to_s.length + 1]
    src << ext
  end
  nme = File.basename(src, '.*')
  nme = '' if nme.length == 1
  ext = File.extname(src)
  (0..ITERATION).each do |i|
    n = File.join(@dir, nme + i.to_s + ext)
    return n unless File.exist?(n)
  end
  raise "Unable to compose a new name: #{src}."
end

#set(src) ⇒ Object



41
42
43
# File 'lib/renamr/existence.rb', line 41

def set(src)
  @src = src
end