1

我正在尝试使用maingem 来制作命令行实用程序。这是在最近的 Ruby Rogues 播客中介绍的。

如果我将所有代码放在一个文件中并需要该文件,那么 rspec 会给我一个错误,因为主 dsl 将 rpsec 视为主实用程序的命令行调用。

我可以将一个方法分解成一个新文件并让 rspec 需要该文件。假设你有这个程序,但想把do_something方法放在一个单独的文件中用 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)   
}

分发/部署具有多个文件的 ruby​​ 命令行程序的便捷方法是什么?也许创造一个宝石?

4

1 回答 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.

于 2013-06-17T13:01:22.530 回答