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
rake
this appears to be not possible. Ultimately the return value for a rake task is determined fromTask#execute
which has anil
return value. You can take a look here. github.com/ruby/rake/blob/master/lib/rake/task.rb#L270 – Taoresult = 'something'
and in task2 I can read the variable. Consider I createdresult
variable outside task scopes, something likeresult = nil
before any namespace/task. This is, assuming you want a task result in other task. – Artillery