如何跳过红宝石需求? [英] How to skip require in ruby?

查看:114
本文介绍了如何跳过红宝石需求?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我可以有条件跳过在Ruby中需要文件吗?

Can I conditionally skip requiring a file in Ruby?

begin
  require 'aws-sdk'
rescue LoadError
  puts "aws-sdk gem not found"
end

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

在上面的代码中,我可以让Ruby不要在 rescue rescue LoadError

之后阅读。整个代码在一个条件,但不雅。
我试过下一步 return

In the above code, can I ask Ruby not to read after rescue LoadError
I can wrap the whole code in an conditional but that is inelegant. I tried next and return.

编辑:在添加一个新问题我是否可以有条件地跳过加载进一步 ruby代码在同一个文件?。抱歉。没有正确提出这个问题

added a new question at Can I conditionally skip loading "further" ruby code in the same file?. sorry. Did not ask this question properly

推荐答案


我已经救出了LoadError,但是我希望如果LoadError被执行。,进一步的代码不应该被执行。在给出的示例中,不应该调用rake任务db:import_to_heroku

i have rescued LoadError but i want that if LoadError is executed., further code should not be executed. In the example given, the rake task db:import_to_heroku should not be called

然后执行:

Then do:

begin
  require 'aws-sdk'

  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
rescue LoadError
  puts "aws-sdk gem not found"
end

这篇关于如何跳过红宝石需求?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆