Class: Renamr::DateAction

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

Overview

Replaces any valid date, e.g. 2020-11-02 or 02-11-2020 with 20201102.

Constant Summary collapse

REG =
/(\d+)-(\d+)-(\d+)/.freeze
PAT =
['%m-%d-%Y', '%d-%m-%Y', '%Y-%m-%d', '%Y-%d-%m'].freeze

Instance Method Summary collapse

Methods inherited from Action

#p2m, #set

Instance Method Details

#date(sub) ⇒ Object



23
24
25
26
27
28
29
30
# File 'lib/renamr/date.rb', line 23

def date(sub)
  PAT.each do |pat|
    return Date.strptime(sub, pat)
  rescue ArgumentError
    # Nothing to do.
  end
  nil
end

#do(src) ⇒ Object



32
33
34
35
36
37
38
39
40
41
42
43
# File 'lib/renamr/date.rb', line 32

def do(src)
  sub = src[REG]
  return src if sub.nil?

  dat = date(sub)
  return src if dat.nil?

  dat = validate(dat)
  return src if dat.nil?

  src.sub!(REG, dat.strftime('%Y%m%d'))
end

#validate(dat) ⇒ Object



15
16
17
18
19
20
21
# File 'lib/renamr/date.rb', line 15

def validate(dat)
  return nil if dat < Date.new(1900, 1, 1)

  return nil if dat > Date.new(2099, 1, 1)

  dat
end