HELLO, I’M SERHAT AND THIS IS MY FANCY TITLE.

Running Rake Tasks in a Loop

Rake tasks in a loop, will only executed once when they are not re-enabled. Take a look to this example:


namespace :yoksis do
  desc 'fetches all references'
  task :references do
    mapping = {
      get_instruction_language: 'UnitInstructionLanguage',
      get_instruction_type: 'UnitInstructionType'
    }

    mapping.each do |action, klass|
      Rake::Task['yoksis:reference'].invoke(action, klass)
    end
  end

  desc 'fetch an individual reference'
  task :reference, %i[soap_method klass] => [:environment] do |_, args|
    puts args[:soap_method]
    puts args[:klass]
  end
end

When you run the yoksis:references task, it will only print out {get_instruction_language: 'UnitInstructionLanguage'} and will skip the second item of the mapping hash.

To solve this, you should re-enable the Rake task like this:

Rake::Task['yoksis:reference'].reenable

The final working version of the task has shown below:

namespace :yoksis do
  desc 'fetches all references'
  task :references do
    mapping = {
      get_instruction_language: 'UnitInstructionLanguage',
      get_instruction_type: 'UnitInstructionType'
    }

    mapping.each do |action, klass|
      Rake::Task['yoksis:reference'].invoke(action, klass)
      Rake::Task['yoksis:reference'].reenable
    end
  end

  desc 'fetch an individual reference'
  task :reference, %i[soap_method klass] => [:environment] do |_, args|
    puts args[:soap_method]
    puts args[:klass]
  end
end

Cheers.

Date:
Categories: tech, ruby, ruby on rails

Share this post!


Blog Comments powered by Disqus.