使用caller 确定您与调用堆栈顶部的距离:
---------------------------------------------------------- Kernel#caller
caller(start=1) => array
------------------------------------------------------------------------
Returns the current execution stack---an array containing strings
in the form ``_file:line_'' or ``_file:line: in `method'_''. The
optional _start_ parameter determines the number of initial stack
entries to omit from the result.
def a(skip)
caller(skip)
end
def b(skip)
a(skip)
end
def c(skip)
b(skip)
end
c(0) #=> ["prog:2:in `a'", "prog:5:in `b'", "prog:8:in `c'", "prog:10"]
c(1) #=> ["prog:5:in `b'", "prog:8:in `c'", "prog:11"]
c(2) #=> ["prog:8:in `c'", "prog:12"]
c(3) #=> ["prog:13"]
这给出了scriptize 的定义
# scriptize.rb
def scriptize
yield ARGV if caller.size == 1
end
现在,作为示例,我们可以使用两个相互需要的库/可执行文件
# libexA.rb
require 'scriptize'
require 'libexB'
puts "in A, caller = #{caller.inspect}"
if __FILE__ == $0
puts "A is the main script file"
end
scriptize { |args| puts "A was called with #{args.inspect}" }
# libexB.rb
require 'scriptize'
require 'libexA'
puts "in B, caller = #{caller.inspect}"
if __FILE__ == $0
puts "B is the main script file"
end
scriptize { |args| puts "B was called with #{args.inspect}" }
所以当我们从命令行运行时:
% ruby libexA.rb 1 2 3 4
in A, caller = ["./libexB.rb:2:in `require'", "./libexB.rb:2", "libexA.rb:2:in `require'", "libexA.rb:2"]
in B, caller = ["libexA.rb:2:in `require'", "libexA.rb:2"]
in A, caller = []
A is the main script file
A was called with ["1", "2", "3", "4"]
% ruby libexB.rb 4 3 2 1
in B, caller = ["./libexA.rb:2:in `require'", "./libexA.rb:2", "libexB.rb:2:in `require'", "libexB.rb:2"]
in A, caller = ["libexB.rb:2:in `require'", "libexB.rb:2"]
in B, caller = []
B is the main script file
B was called with ["4", "3", "2", "1"]
所以这显示了使用 scriptize 和 if $0 == __FILE__ 的等价性
但是,请考虑:
-
if $0 == __FILE__ ... end 是一个标准的 ruby 习语,阅读您的代码的其他人很容易识别
-
require 'scriptize'; scriptize { |args| ... } 为相同的效果输入更多内容。
为了真正值得这样做,您需要在 scriptize 的主体中具有更多的通用性 - 初始化一些文件、解析参数等。一旦变得足够复杂,您最好还是分解以不同的方式进行更改 - 可能通过脚本化您的类,因此它可以实例化它们并执行主脚本主体,或者拥有一个根据名称动态需要您的类之一的主脚本。