3

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.

Jack
  • 497
  • 5
  • 16
  • 3
    Exit will terminate the entire script, not just the task. Can't you just take it out? – tpbowden Mar 27 '16 at 17:13
  • you wrote "checks for a value to be present, if it is not then exit the task" but in your 'check' method you are running "exit" if the value IS present (not nil) – emery Mar 27 '16 at 17:17
  • possible duplicate of http://stackoverflow.com/questions/2316475/how-do-i-return-early-from-a-rake-task – emery Mar 27 '16 at 17:18
  • Is there a reason, why you don't use prerequisites like `task main: :environment => ['tester:first', 'tester:second','tester:third']`? – knut Mar 27 '16 at 18:14
  • @knut Not really, how would this apply to my problem? – Jack Mar 27 '16 at 19:06
  • I don't think it apply to your problem, but it looks strange and not rake-like. As tpbowden mentions: you need no exit. Inside a method you may use return, inside a rake task use break. – knut Mar 27 '16 at 20:32

1 Answers1

3

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

emery
  • 8,603
  • 10
  • 44
  • 51
  • 1
    Thanks,I have applied your solution and it works fine! I will go this way! – Jack Mar 28 '16 at 10:16
  • another way to write the if/else/end in the check method would be to use a ternary: "return value.nil? ? nil : value" – emery Mar 31 '16 at 01:26