1

I am trying to use the main gem for making command line utilities. This was presented in a recent Ruby Rogues podcast.

If I put all the code in one file and require that file, then rspec gives me an error, as the main dsl regards rpsec as a command line invocation of the main utility.

I can break out a method into a new file and have rspec require that file. Suppose you have this program, but want to put the do_something method in a separate file to test with rspec:

require 'main'

def do_something(foo)
  puts "foo is #{foo}"
end    

Main {
  argument('foo'){
    required                    # this is the default
    cast :int                   # value cast to Fixnum
    validate{|foo| foo == 42}   # raises error in failure case 
    description 'the foo param' # shown in --help
  }
  do_something(arguments['foo'].value)   
}

What is the convenient way to distribute/deploy a ruby command line program with multiple files? Maybe create a gem?

1 Answer 1

1

You are on the right track for testing - basically you want your "logic" in separate files so you can unit test them. You can then use something like Aruba to do an integration test.

With multiple files, your best bet is to distribute it as a RubyGem. There's lots of resources out there, but the gist of it is:

  • Put your executable in bin
  • Put your files in lib/YOUR_APP/whatever.rb where "YOUR_APP" is the name of your app. I'd also recommend namespacing your classes with modules named for your app
  • In your executable, require the files in lib as if lib were in the load path
  • In your gemspec, make sure to indicate what your bin files are and what your lib files are (if you generate it with bundle gem and are using git, you should be good to go)

This way, your app will have access to the files in lib at runtime, when installed with RubyGems. In development, you will need to either do bundle exec bin/my_app or RUBYLIB=lib bin/my_app. Point is, RubyGems takes care of the load path at runtime, but not at development time.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.