既可以loaded/required又可以作为程序使用的库
A library that can be loaded/required as well as be used as a program
我想写一个小的Ruby库。有时我想将它用作独立的 CLI 应用程序,有时又用作可加载的库。我怎样才能做到这一点?
如果是简单的文件,一般的做法是:
#!/usr/bin/env ruby
# content of the library
...
if [=10=] == __FILE__
# command to be executed only when the file is called by a command
end
如果你想把它变成gem,标准的方法是把可执行的Ruby脚本写在[=13=下面的一个文件里(比方说foo
) ] 目录中的 gem 目录,并将以下内容添加到 *.gemspec
文件中:
Gem::Specification.new do |s|
...
s.executables << "foo"
...
end
我想写一个小的Ruby库。有时我想将它用作独立的 CLI 应用程序,有时又用作可加载的库。我怎样才能做到这一点?
如果是简单的文件,一般的做法是:
#!/usr/bin/env ruby
# content of the library
...
if [=10=] == __FILE__
# command to be executed only when the file is called by a command
end
如果你想把它变成gem,标准的方法是把可执行的Ruby脚本写在[=13=下面的一个文件里(比方说foo
) ] 目录中的 gem 目录,并将以下内容添加到 *.gemspec
文件中:
Gem::Specification.new do |s|
...
s.executables << "foo"
...
end