Class: CleanFiles::Cleaner

Inherits:
Object
  • Object
show all
Defined in:
lib/clean_files/cleaner.rb

Defined Under Namespace

Classes: SimpleFile

Constant Summary collapse

VALID_OPTIONS =
[:threshold, :pretend, :verbose, :recursive]
VALID_INTERVALS =
[:hourly, :daily, :weekly, :monthly, :yearly]
TIME_INTERVALS =
[:hour,   :day,   :cweek, :month, :year]

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(paths, options = {}) ⇒ Cleaner

Returns a new instance of Cleaner.



15
16
17
18
19
20
21
22
23
24
# File 'lib/clean_files/cleaner.rb', line 15

def initialize(paths, options = {})
  @paths = [paths].flatten
  @options = options.reverse_merge(:threshold => 30.days.ago)
  options.assert_valid_keys(VALID_OPTIONS + VALID_INTERVALS)
  given_intervals = VALID_INTERVALS & options.keys
  if given_intervals.present?
    lowest_selected_position = VALID_INTERVALS.index(given_intervals.first)
    @key_intervals = TIME_INTERVALS[lowest_selected_position..-1]
  end
end

Instance Attribute Details

#optionsObject (readonly)

Returns the value of attribute options.



5
6
7
# File 'lib/clean_files/cleaner.rb', line 5

def options
  @options
end

#pathsObject (readonly)

Returns the value of attribute paths.



5
6
7
# File 'lib/clean_files/cleaner.rb', line 5

def paths
  @paths
end

Instance Method Details

#filesObject



32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
# File 'lib/clean_files/cleaner.rb', line 32

def files
  if paths.any?{|path| path.include?('*')}
    paths.map!{|path| Dir.glob(path)}
    paths.flatten!
  end
  @_files ||= paths.map do |file_path|
    begin
      SimpleFile.new(file_path, File.stat(file_path))
    rescue Errno::EOPNOTSUPP
      nil
    rescue Errno::ENOENT => e
      puts e.to_s
      exit -2
    end
  end.compact.select do |file|
    file.file? || (options[:recursive] && file.directory?)
  end.sort_by(&:ctime)
end

#files_before_thresholdObject



55
56
57
# File 'lib/clean_files/cleaner.rb', line 55

def files_before_threshold
  files.select{|file| file.ctime < options[:threshold]}
end

#files_to_deleteObject



51
52
53
# File 'lib/clean_files/cleaner.rb', line 51

def files_to_delete
  files_before_threshold - files_to_preserve
end

#files_to_preserveObject



59
60
61
62
63
64
65
66
67
# File 'lib/clean_files/cleaner.rb', line 59

def files_to_preserve
  return [] if @key_intervals.nil?
  files_before_threshold.group_by do |file|
    cdate = file.ctime.to_datetime
    @key_intervals.map{|interval| cdate.send(interval)}
  end.map do |_, files|
    files.first
  end
end

#startObject



26
27
28
29
30
# File 'lib/clean_files/cleaner.rb', line 26

def start
  files = files_to_delete.map(&:path)
  puts files.join("\n") if options[:verbose]
  FileUtils.rm_rf(files, :noop => !!options[:pretend])
end