Search code examples
rubyrubygemsrequire

How to skip require in 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

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


Solution

  • 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