Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I run Rake tasks within a Ruby script?

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?

like image 356
Mando Escamilla Avatar asked Aug 06 '08 15:08

Mando Escamilla


People also ask

What is a Ruby Rake task?

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.

How do I list a Rake task?

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.


2 Answers

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} 
like image 151
titanous Avatar answered Oct 01 '22 13:10

titanous


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.

like image 41
Kelvin Avatar answered Oct 01 '22 15:10

Kelvin