Class: Deblank::Optionparser
- Inherits:
-
Object
- Object
- Deblank::Optionparser
- Defined in:
- lib/deblank.rb
Overview
Parser for the command line options. The class method parse! does the job.
Class Method Summary collapse
-
.correct_encoding(string) ⇒ Object
Corrects the encoding for (seemingly) CP850 encoded strings from ‘CP850’ to ‘Windows-1252’.
-
.parse!(argv) ⇒ Object
Parses the command line options from
argv.
Class Method Details
.correct_encoding(string) ⇒ Object
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.]
122 123 124 125 126 |
# 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) ⇒ Object
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.
51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 |
# File 'lib/deblank.rb', line 51 def self.parse!(argv) = { :files => nil, :simulate => false } opt_parser = OptionParser.new do |opt| opt. = "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 [: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 [:files] = Array.new(argv).map do |filename| correct_encoding(filename).encode('UTF-8') end argv.clear end |