0

If I have a task defined in my Rakefile that looks like this:

MyLibrary::CopySrcTask.new(:copySrc) do |task|
  puts "Copying source"
  task.src_dir = 'src/'
  task.destination = 'build/lib/'
end

I've come to realize that the puts in the above task will get executed even if I specify a rake target for which that :copySrc task is not executed. I'm wondering if there's a way to specify the puts in a late-binding manner such that it will only get executed if/when the rake task itself gets executed?

This may not seem like a big deal, but it would certainly allow for easier debugging, and furthermore, it becomes a much bigger deal when you consider a case like this:

MyLibrary::CopySrcTask.new(:copySrc) do |task|
  task.src_dir = complex_function_which_affects_filesystem()
  task.destination = 'build/lib/'
end

Now in this case, it's essentially the same problem as with the puts getting evaluated even though the task isn't being run, but now instead of just a superfluous puts call, it's doing some whole operation which messes up the file system. Is there any way to make it so that all of this code inside the task initialization is only executed when the task itself is executed?

If something like this would work, it would be great:

MyLibrary::CopySrcTask.new(:copySrc) do |task|
  lambda do  # this code will only be run if the task gets run
    puts "Copying source"
    task.src_dir = complex_function_which_affects_filesystem()
    task.destination = 'build/lib/'
  end
end

I should note that the task I'm using is from a library, so I can't just edit the task itself.

Dasmowenator
  • 5,505
  • 5
  • 36
  • 50

1 Answers1

0

This is the solution/hack I found that seems to work:

task :copySrc do |t|
  MyLibrary::CopySrcTask.new(:internalCopySrc) do |task|
    puts "Copying source"
    task.src_dir = complex_function_which_affects_filesystem()
    task.destination = 'build/lib/'
  end
  Rake::Task[:internalCopySrc].invoke
end

Wrapping each library task in another task, then manually invoking the child task... It's not pretty, but it works.

Dasmowenator
  • 5,505
  • 5
  • 36
  • 50