How to Run Rake Tasks Within a Ruby Script

How do I run Rake tasks within a Ruby script?

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}

Rails how to run rake task

You can run Rake tasks from your shell by running:

rake task_name

To run from from Ruby (e.g., in the Rails console or another Rake task):

Rake::Task['task_name'].invoke

To run multiple tasks in the same namespace with a single task, create the following new task in your namespace:

task :runall => [:iqmedier, :euroads, :mikkelsen, :orville] do
# This will run after all those tasks have run
end

Ruby: run rake task to execute ruby scripts

If I understand you correctly you have a folder with some ruby scripts and you are trying to run a rake task that is located in the same folder. I assume you are not using any application framework like Rails (because you did tag the question only with "Ruby").

Do you have a Rakefile in same directory? If so does it contain a statement to load the specific files to run?

# Rakefile
#!/usr/bin/env rake
load 'export_stats.rake'

Run two ruby scripts from rake task

It might be easier to require the ruby class directly into your rake task, but if you want to run a script from a rake task you can run any shell code in Ruby using backticks, like this:

`ruby first_script.rb param1 param2 | ruby second_script.rb`

How do I run rake tasks within my rails application

If you wish this rake code to run during the request cycle then you should avoid running rake via system or any of the exec family (including backticks) as this will start a new ruby interpreter and reload the rails environment each time it is called.

Instead you can call the Rake commands directly as follows :-

require 'rake'

class SomeModel <ActiveRecord::Base

def self.run_rake(task_name)
load File.join(RAILS_ROOT, 'lib', 'tasks', 'custom_task.rake')
Rake::Task[task_name].invoke
end
end

Note: in Rails 4+, you'll use Rails.root instead of RAILS_ROOT.

And then just use SomeModel.run_rake("ts:reindex")

The key parts here are to require rake and make sure you load the file containing the task definitions.

Most information obtained from http://railsblogger.blogspot.com/2009/03/in-queue_15.html

How to run a rake task by command line in rails

  1. Run rake -T -A from your Rails home directory to see all the tasks that rake knows about. Yours must be in that list for rake to run it.
  2. By default, in a Rails app, rake looks in the lib/tasks directory and its subdirectories for your .rake files. Check that. (I suspect this is the problem.)


Related Topics



Leave a reply



Submit