Class: FilenameCleaner::Utils

Inherits:
Object
  • Object
show all
Defined in:
lib/filename_cleaner/utils.rb

Constant Summary collapse

DOT =
'.'

Class Method Summary collapse

Class Method Details

.sanitize(filename) ⇒ String

Clean the the input string to remove the special characters

Parameters:

  • filename (String)

    input file

Returns:

  • (String)

    the new file name with special characters replaced or removed.



25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
# File 'lib/filename_cleaner/utils.rb', line 25

def sanitize(filename)
  # remove anything that is not letters, numbers, dash, underscore or space
  # Note: we intentionally ignore dot from the list
  filename.gsub!(/[^0-9A-Za-z\-_ ]/, DOT)

  # replace multiple occurrences of a given char with a dot
  ['-', '_', ' '].each do |c|
    filename.gsub!(/#{Regexp.quote(c)}+/, DOT)
  end

  # replace multiple occurrence of dot with one dot
  filename.gsub!(/#{Regexp.quote(DOT)}+/, DOT)

  filename
end

.sanitize_filename(filename, sep_char = nil) ⇒ Object

Sanitize filename that have the extension

Parameters:

  • filename (String)

    the input filename with extension



9
10
11
12
13
14
15
16
17
18
19
# File 'lib/filename_cleaner/utils.rb', line 9

def sanitize_filename(filename, sep_char = nil)
  extension = File.extname(filename)

  if extension.empty?
    replace_dot!(sanitize(filename), sep_char)
  else
    name_only = File.basename(filename, ".*")
    name_only = replace_dot!(sanitize(name_only), sep_char)
    "#{name_only}#{extension}"
  end
end