[英]Best way to stop load script execution in Ruby on Rails's IRB
尋找在Ruby on Rails的IRB上退出已加載腳本的最佳方法。 Kernel.exit和Kernel.abort會讓你完全退出IRB會話。 理想情況下,這會在某些條件標准上發生。
我的腳本/ my_script.rb:
puts "My Script is running!"
# if some criteria, stop execution of this script without stoping IRB
puts "This will never happen"
理想的結果:
$ rails console
irb(main):001:0> load 'script/my_script.rb'
My Script is running!
irb(main):002:0>
使用__END__
關鍵字來停止解析器。
puts "My Script is running!"
__END__
puts "This will never happen"
...
或者只是注釋掉腳本的其余部分(如果在___END__
之后需要格式良好的DATA
流)
puts "My Script is running!"
=begin
puts "This will never happen"
...
=end
如果你需要根據邏輯而不是在固定點提前退出,你可以將腳本的主體放在一個函數中,然后盡早返回。
def do_work
puts "My Script is running!"
...
return if exit_condition?
puts "This will never happen if exit condition is true"
...
end
do_work
或者,將您的腳本放在開始塊中並挽救您引發的異常
begin
puts "My Script is running!"
raise SystemExit if exit_condition?
puts "This will never happen if exit condition is true"
rescue SystemExit
end
我現在能想到的最好的解決方案是引發一個腳本無法處理的異常。 但是,您獲得的堆棧跟蹤輸出可能是不合需要的。
腳本/ my_script.rb
puts "My Script is running!"
raise "quiting, but I'm not happy about it"
puts "This will never happen"
結果:
irb(main):001:0> load 'script/my_script.rb'
My Script is running!
RuntimeError: quiting, but I'm not happy about it
from script/my_script.rb:2:in `<top (required)>'
from /usr/local/rbenv/versions/1.9.3-p374/lib/ruby/gems/1.9.1/gems/activesupport-3.2.13/lib/active_support/dependencies.rb:245:in `load'
from /usr/local/rbenv/versions/1.9.3-p374/lib/ruby/gems/1.9.1/gems/activesupport-3.2.13/lib/active_support/dependencies.rb:245:in `block in load'
from /usr/local/rbenv/versions/1.9.3-p374/lib/ruby/gems/1.9.1/gems/activesupport-3.2.13/lib/active_support/dependencies.rb:236:in `load_dependency'
from /usr/local/rbenv/versions/1.9.3-p374/lib/ruby/gems/1.9.1/gems/activesupport-3.2.13/lib/active_support/dependencies.rb:245:in `load'
from (irb):1
from /usr/local/rbenv/versions/1.9.3-p374/lib/ruby/gems/1.9.1/gems/railties-3.2.13/lib/rails/commands/console.rb:47:in `start'
from /usr/local/rbenv/versions/1.9.3-p374/lib/ruby/gems/1.9.1/gems/railties-3.2.13/lib/rails/commands/console.rb:8:in `start'
from /usr/local/rbenv/versions/1.9.3-p374/lib/ruby/gems/1.9.1/gems/railties-3.2.13/lib/rails/commands.rb:41:in `<top (required)>'
from script/rails:6:in `require'
from script/rails:6:in `<main>'
irb(main):002:0>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.