tags:

views:

41

answers:

2

I am building a little tool in ruby for creating directories and files based on commands that I issue it from the command line. I would like for this to work on Mac, Windows, and Linux.

I am of course new to ruby and I know how to right a simple script and call it to run from the command line. What I would like to do is be able to navigate anywhere on my system call the name of the app and pass args so that I can have it create files and directories based in my current location in the command line.

example $> myapp -create mydirectoryname

So what is the best way to do this. Could you guys point me to a resource that walks me through this? Thanks so much.

-Matthew

A: 

If you want something standard, See Getoptlong

require 'getoptlong'

opts = GetoptLong.new(
  [ '--help', '-h', GetoptLong::NO_ARGUMENT ],
  [ '--repeat', '-n', GetoptLong::REQUIRED_ARGUMENT ],
  [ '--name', GetoptLong::OPTIONAL_ARGUMENT ]
)

dir = nil
name = nil
repetitions = 1
opts.each do |opt, arg|
  case opt
    when '--help'
      puts "Help here..."
    when '--repeat'
      repetitions = arg.to_i
    when '--name'
      if arg == ''
        name = 'John'
      else
        name = arg
      end
  end
end

if ARGV.length != 1
  puts "Missing dir argument (try --help)"
  exit 0
end

dir = ARGV.shift

Dir.chdir(dir)
for i in (1..repetitions)
  print "Hello"
  if name
    print ", #{name}"
  end
  puts
end

Example command line:

hello -n 6 --name -- /tmp

I personally like trollop, it is not included in the standard library.

Once you have the command line stuff going, see FileUtils module to create the directory:

require 'fileutils'
FileUtils.mkdir("dir")
duncan
A: 

Getoptlong mentioned by duncan is part of ruby core, but there are much nicer external libraries that let you do it in a cleaner/easier way.

I recommend you look at Choice. The examples given there should be enough to get you going.

ehsanul
I pointed him to trollop, which is IMO the best :-)
duncan
Ahh, I had forgotten about trollop without ever having used it. Thanks, looks neat :)
ehsanul