Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to return some value from rake task

How can I return some value from a Rake task in ruby.

Sample code:

namespace tasks
    task task1: :environment do |task|
      log = "Running task"
      puts log
      log << "Done"
      return log # suggest how to do this
    end
end

I am running the rake task as: Rake::Task['tasks:task1'].invoke. How can I get the return value in a variable as follows:

result = Rake::Task['tasks:task1'].invoke
like image 882
Rajesh Paul Avatar asked Jul 07 '26 15:07

Rajesh Paul


2 Answers

Assuming you want the task result in other task:


config = ''

task :load_config do
  config = 'some config' # this could be reading from a file or API
end

# this tasks depends on the other
task use_config: [:load_config] do
  puts config
end

Then:

$ bundle exec rake use_config
some config
like image 61
Juan José Ramírez Avatar answered Jul 09 '26 21:07

Juan José Ramírez


Call the Rake's action directly.

Using @vigo's example because it's simple.

task :return_a_value do
  '123'
end
result = Rake::Task['return_a_value'].actions.first.call

puts result #=> "123"

I found this out by digging through the various methods of the Rake Task in the console and this appeared to work without having to run the task twice, like @vido's answer.

However, the only caveat I've found is that I couldn't figure out how to pass arguments to the Rake Task using this method. Using .call( "myargument" ) didn't work. If you can figure out how to do this, I'd be grateful if you shared it. Thanks!

Update: Figured it out.

After a little more experimentation, I figured out how to use this method while passing arguments to the Rake Task. You just have to pass a Hash of the arguments as the second parameter and nil as the first, like so:

task :return_a_value, :mystring do
  mystring
end
result = Rake::Task['return_a_value'].actions.first.call( nil, { mystring: "hellow there" } )

puts result #=> "hellow there"

It has the added benefit of naming the parameters you pass to the Rake Task, which is a nice bonus.


Versions

  • Rails: 7.0.7
  • Ruby: 3.2.2
like image 31
Joshua Pinter Avatar answered Jul 09 '26 19:07

Joshua Pinter



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!