class Deblank::Optionparser
Parser for the command line options. The class method parse! does the job.
Public Class Methods
correct_encoding(string)
click to toggle source
Corrects the encoding for (seemingly) CP850 encoded strings from ‘CP850’ to ‘Windows-1252’.
Returns a copy of string
with corrected encoding or string
.
[On the Windows test machine (which uses code page 850 for the command prompt) the command line arguments are interpreted by Ruby as CP850 encoded strings but actually are Windows-1252 encoded.]
# File lib/deblank.rb, line 122 def self.correct_encoding(string) return string unless string.encoding == Encoding::CP850 string.dup.force_encoding('Windows-1252') end
parse!(argv)
click to toggle source
Parses the command line options from argv
. (argv
is cleared). Might print out help or version information.
argv
- array with the command line options
Returns a hash containing the option parameters.
# File lib/deblank.rb, line 51 def self.parse!(argv) options = { :files => nil, :simulate => false } opt_parser = OptionParser.new do |opt| opt.banner = "Usage: #{PROGNAME} [options] file[s]" opt.separator %Q{ deblank renames files and replaces or removes special characters like spaces, parentheses, or umlauts. The new filename will only contain the following characters: ____#{NameConverter.default_valid_chars_to_s} Spaces are replaced by underscores, German umlauts and eszett are transliterated, all other invalid characters are removed. Options }.gsub(/^ +/, '').gsub(/^____/, ' ') # process --version and --help first, # exit successfully (GNU Coding Standards) opt.on_tail('-h', '--help', 'Print a brief help message and exit.') do puts opt_parser puts "\nReport bugs on the #{PROGNAME} home page: <#{HOMEPAGE}>" exit end opt.on_tail('-v', '--version', 'Print a brief version information and exit.') do puts "#{PROGNAME} #{VERSION}" puts COPYRIGHT exit end opt.on('-l', '--list', 'List the used character substitutions.') do puts NameConverter.default_substitutions_to_s exit end opt.on('-n', '--no-act', 'Do not rename files, only display what would happen.') do options[:simulate] = true end opt.separator '' end opt_parser.parse!(argv) # only file[s] should be left (at least 1 argument) raise(ArgumentError, 'wrong number of arguments') if argv.size < 1 options[:files] = Array.new(argv).map do |filename| correct_encoding(filename).encode('UTF-8') end argv.clear options end