Search code examples
rubyrakecommand-line-interface

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?


Solution

  • 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}