是否有可能在不退出整个过程的情况下有条件地阻止Ruby评估所需的文件?
我require
主文件中的第二个文件,并希望从第二个文件中的某个点返回而不退出整个过程。 回报应该是有条件的。
# file1.rb puts "In file 1" require 'file2' puts "Back in file 1" # file2.rb puts "In file 2" # <= A puts "Still in file 2"
运行file1.rb
,我想看到的输出是:
In file 1 In file 2 Back in file 1
请注意, Still in file 2
中的Still in file 2
不会打印,而Back in file 1
中的Back in file 1
会打印。 我能在A
点做些什么来实现这个目标吗?
我不能使用exit
/ exit!
/ abort
here,因为Back in file 1
将永远不会打印。 我可以使用raise
/ fail
,但要做到这一点,我将不得不rescue
失败的require
。 我希望找到一种不涉及改变file1.rb
。
更新 :
添加了“顶级返回”function。
__END__
以下的__END__
不会被执行 。
# file2.rb puts "In file 2" __END__ puts "Still in file 2" # Never gets called
我不知道任何破坏所需文件的官方方法,特别是因为有几种require
方法(例如,需要捆绑猴子补丁)
我能想到的最好的解决方案是使用rubys throw-catch控制流程。 我不确定你是否有条件确定执行是否应尽早返回,但这应该能够应对大多数情况
# file1.rb puts "In file 1" catch(:done) do require 'file2' end puts "Back in file 1" # file2.rb puts "In file 2" throw :done puts "Still in file 2" # Never gets called
更新 :
此function已添加 。
原文 :
Commenter matt指出,function4840,这正是我所要求的, 自2011年6月以来一直在讨论 。 此外,该function在2015年11月的核心团队会议中仍在讨论有关新Rubyfunction的问题。
设计这样的function涉及很多困难; 为了列出优缺点,我强烈建议查看讨论。
建议的function允许在使用以下任何顶级语句时退出所需文件:
if condition return end while condition # ... return end begin # ... return rescue # ... return ensure # ... return end
并且它不会在以下语句中退出所需的文件:
class Foo return # LocalJumpError end def foo return # returns from method, not from required file end proc do return # LocalJumpError end x = -> { return } # returns as from lambda, not from required file
由于该function仍然没有实现,我已经授予steenslag赏金,以便成功解决问题(如原文所写),如果不是精神。
是否可以使用方法? 它仍将解析方法但不会执行。 就像是 :
#file1.rb puts "In file 1" require 'file2' puts "Back in file 1" a_method #file2.rb puts "In file 2" # <= A def a_method puts "Still in file 2" end