How do I force RAILS_ENV in a rake task?

For this particular task, you only need to change the DB connection, so as Adam pointed out, you can do this: namespace :db do namespace :test do task :reset do ActiveRecord::Base.establish_connection(‘test’) Rake::Task[‘db:drop’].invoke Rake::Task[‘db:create’].invoke Rake::Task[‘db:migrate’].invoke ActiveRecord::Base.establish_connection(ENV[‘RAILS_ENV’]) #Make sure you don’t have side-effects! end end end If your task is more complicated, and you need other aspects … Read more

Run rake task in controller

I agree with ddfreynee, but in case you know what you need code can look like: require ‘rake’ Rake::Task.clear # necessary to avoid tasks being loaded several times in dev mode Sample::Application.load_tasks # providing your application name is ‘sample’ class RakeController < ApplicationController def run Rake::Task[params[:task]].reenable # in case you’re going to invoke the same … Read more

How do I run a rake task from Capistrano?

A little bit more explicit, in your \config\deploy.rb, add outside any task or namespace: namespace :rake do desc “Run a task on a remote server.” # run like: cap staging rake:invoke task=a_certain_task task :invoke do run(“cd #{deploy_to}/current; /usr/bin/env rake #{ENV[‘task’]} RAILS_ENV=#{rails_env}”) end end Then, from /rails_root/, you can run: cap staging rake:invoke task=rebuild_table_abc

How to run Rake tasks from within Rake tasks?

If you need the task to behave as a method, how about using an actual method? task :build => [:some_other_tasks] do build end task :build_all do [:debug, :release].each { |t| build t } end def build(type = :debug) # … end If you’d rather stick to rake‘s idioms, here are your possibilities, compiled from past … Read more

How to pass command line arguments to a rake task

You can specify formal arguments in rake by adding symbol arguments to the task call. For example: require ‘rake’ task :my_task, [:arg1, :arg2] do |t, args| puts “Args were: #{args} of class #{args.class}” puts “arg1 was: ‘#{args[:arg1]}’ of class #{args[:arg1].class}” puts “arg2 was: ‘#{args[:arg2]}’ of class #{args[:arg2].class}” end task :invoke_my_task do Rake.application.invoke_task(“my_task[1, 2]”) end # … Read more