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
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
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!
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With