2013-04-09 78 views
3

尋找在Ruby on Rails的IRB中退出加載腳本的最佳方式。 Kernel.exit & Kernel.abort會將您從IRB會話中彈出。理想情況下,這會發生在一些條件標準上。在Ruby on Rails的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> 

回答

3

使用__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 
+0

根據原始問題有效答案。如果它有條件退出將無法工作。 (我已更新該帖子以包含條件要求。) – spyle

+0

@spyle只是在解決該問題的過程中,請參閱更新。 – dbenhur

+0

功能,當然!做得好。 – spyle

0

我現在能想到的最好的解決辦法是提高不是由腳本處理的異常。但是,您會得到堆棧跟蹤輸出,這可能是不可取的。

腳本/ 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> 
+0

你可以拋出異常,那麼拯救它,什麼也不做。 –