Search code examples
ruby-on-railsrubyrakerake-task

Exit from one of a series of Rake tasks and continue with the next


I have this main Rake task

  namespace :crawler do

  task main: :environment do
  Rake::Task['tester:first'].execute
  Rake::Task['tester:second'].execute
  Rake::Task['tester:third'].execute
  end

  end

Every task runs a piece of code that checks for a value to be present, if it is not then exit the task and continue with the next one. Actually the code is the following but it is not working

def check(value)
 if !value.nil?
   return value
 else
   exit
 end
end

When I reach the Exit part, the whole program exits,and the other tasks don't get executed.


Solution

  • Try using "next" from within your Rake task to jump to the next task if your check method returns nil.

    You can use a conditional inside your "check" function to return the value if it exists, or to return nil if the value is nil. Then, if check returns nil, you can use next (not exit) to skip to the next task.

    task :main do
      Rake::Task['first'].execute(value: 'Hello, Rake world!')
      Rake::Task['second'].execute
    end
    
    task :first do |_t, args|
      value = args[:value]
      next if check(value).nil?
      puts 'the value is: ' + value
    end
    
    task :second do
      puts 'the second task'
    end
    
    def check(value)
      if value.nil?
        return nil
      else
        return value
      end
    end
    

    Using "next" inside the function definition will not work. You can only skip to the next rake task from inside the current rake task