file1 需要file2,我希望能够file2在某些条件下取消评估而不退出整个过程.
# file1.rb
puts "In file 1"
require 'file2'
puts "Back in file 1"
# file2.rb
puts "In file 2"
# return if some_conditional
puts "Still in file 2"
Run Code Online (Sandbox Code Playgroud)
运行时file1,我想看到的输出是:
In file 1
In file 2
Back in file 1
Run Code Online (Sandbox Code Playgroud)
目标是Still in file 2永不打印,同时Back in file 1打印.我能做些什么才能做到file2这一点?
我无法使用exit/ exit!/ abort这里,因为Back in file 1永远不会打印.我可以使用raise/ fail,但为了做到这一点,我将不得不改变file1和rescue …
如果找不到库(通过 require 加载),我可以有条件地跳过在同一文件中加载“更多”ruby 代码吗?
begin
require 'aws-sdk'
rescue LoadError
puts "aws-sdk gem not found"
return #does not work. nor does next
end
# code after here should not be executed as `aws-sdk` gem was not found
puts "=== should not get executed"
namespace :db do
desc "import local postgres database to heroku. user and database name is hardcoded"
task :import_to_heroku => [:environment, "db:dump_for_heroku"] do
# code using aws-sdk gem
end
end
Run Code Online (Sandbox Code Playgroud)
在上面的代码中,我可以要求 Ruby 在点击 rescue LoadError.
类似于提前返回,但用于加载文件而不是函数。
需要它,因为我有一个需要aws-sdk …