Can I use Ruby's OptionParser to accept an arbitrary argument pattern? -


Assuming I have a simple Ruby app where I want the first argument (if any) to specify the environment I have not given any argument if it is default with Test , development or PRODUCTION ( DEVELOPMENT ). For example,

  ruby ​​myapp.rb test  

will be run in test mode. In addition, short stories should be accepted, for example

  ruby ​​myapp.rb t  

for app test Will run in mode and

  ruby ​​myapp.rb dev  

in DEVELOPMENT mode.

I want to use, but it behaves very oddly if myapp.rb is

  'optparse' environment requirement = 'development' option * option Parser New opts.on ('test') {environment = 'test'} opts.on ('output') (environment = 'production') opts.parse! (ARGV)  

then the environment output any argument I pass; For some reason, opts.on ('output') always executes its block (if I use a flag-style string like '-production' instead of I do not use it, so it is not.) And there is no way for it that I'm looking for OptionParser for strings that start with 'T', rather than the exact string 'test'.

It is possible that OptionParser is the wrong tool for the job, obviously it would be trivial to split ARGV. I am thinking that what is happening with this behavior is on Ruby 1.9.2

provided you use parsing! Any logic handled by the method, opts.on call has been stripped from the ARGV array destructive . This means that ARGV is the original content of the parsed array! After the method they will not remain flags.

I recommend parsing the remaining balance manually by arguing ARGV with an array of 'test' and 'output'.

Check the doctor:


Comments