How to skip require in ruby?

房东的猫 提交于 2020-01-04 11:12:32

问题


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

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.

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


回答1:


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



回答2:


Maybe add an exit after the log:

begin
  require 'aws-sdk'
rescue LoadError
  puts "aws-sdk gem not found"
  exit
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

Also the abort function is to log and exit in the same call:

abort("aws-sdk gem not found")



回答3:


The "top-level return" feature has been added.

It is now possible to use the return keyword at the top level, which as you say, did not work at the time the question was asked. Further discussion here.



来源:https://stackoverflow.com/questions/14522350/how-to-skip-require-in-ruby

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!