4

在 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>
4

2 回答 2

4

使用__END__关键字停止解析器。

puts "My Script is running!"
__END__
puts "This will never happen"
...

或者只是注释掉脚本的其余部分(如果您需要在DATA之后的格式正确的流___END__

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
于 2013-04-09T16:27:39.707 回答
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>
于 2013-04-09T16:24:06.837 回答