I have a Rakefile
with a Rake task that I would normally call from the command line:
rake blog:post Title
I'd like to write a Ruby script that calls that Rake task multiple times, but the only solution I see is shelling out using `` (backticks) or system
.
What's the right way to do this?
Rake is a popular task runner for Ruby and Rails applications. For example, Rails provides the predefined Rake tasks for creating databases, running migrations, and performing tests. You can also create custom tasks to automate specific actions - run code analysis tools, backup databases, and so on.
You can get a list of Rake tasks available to you, which will often depend on your current directory, by typing rake --tasks . Each task has a description, and should help you find the thing you need.
from timocracy.com:
require 'rake' def capture_stdout s = StringIO.new oldstdout = $stdout $stdout = s yield s.string ensure $stdout = oldstdout end Rake.application.rake_require 'metric_fetcher', ['../../lib/tasks'] results = capture_stdout {Rake.application['metric_fetcher'].invoke}
This works with Rake version 10.0.3:
require 'rake' app = Rake.application app.init # do this as many times as needed app.add_import 'some/other/file.rake' # this loads the Rakefile and other imports app.load_rakefile app['sometask'].invoke
As knut said, use reenable
if you want to invoke multiple times.
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