Class: String

Inherits:
Object
  • Object
show all
Defined in:
lib/crowd_support/core_ext/string.rb

Instance Method Summary collapse

Instance Method Details

#next_filenameObject

Returns a filename that doesn’t already exist.

source: www.ruby-forum.com/topic/191831



5
6
7
8
9
10
11
12
13
# File 'lib/crowd_support/core_ext/string.rb', line 5

def next_filename
  count = 0
  unique_name = dup
  while File.exists?(unique_name)
    count += 1
    unique_name = "#{File.join(File.dirname(dup), File.basename(dup, ".*"))}_#{count}#{File.extname(dup)}"
  end
  unique_name
end

#sanitize_filenameObject

Returns a filename with all non-alphanumeric characters removed.

source: stackoverflow.com/a/10823131



18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
# File 'lib/crowd_support/core_ext/string.rb', line 18

def sanitize_filename
  # Split the name when finding a period which is preceded by some
  # character, and is followed by some character other than a period,
  # if there is no following period that is followed by something
  # other than a period (yeah, confusing, I know)
  fn = dup.split /(?<=.)\.(?=[^.])(?!.*\.[^.])/m

  # We now have one or two parts (depending on whether we could find
  # a suitable period). For each of these parts, replace any unwanted
  # sequence of characters with an underscore
  fn.map! { |s| s.gsub /[^a-z0-9\-]+/i, '_' }

  # Finally, join the parts with a period and return the result
  return fn.join '.'
end