Geo
Geo

Reputation: 96827

How can I create a rake task that will always run when any Rake task is ran?

From what I remember, in the documentation is specified that in the test environment, the database is always cleared even when you run rake ( with no arguments ). I'd like to achieve such a thing, so that it doesn't matter if I run a task or not, when I run rake, there's always a Rake task being executed. Is this possible? Is this where the default task kicks in?

Upvotes: 2

Views: 1300

Answers (1)

vlasits
vlasits

Reputation: 2235

Create a file called rakefile in the directory you want to run the task from. This code will make it so that if you just type "rake" my_default_task will run:

  task :default => 'my_default_task'

  task :my_default_task do
     puts "Now I am doing the task that Tempus wants done when he/she types 'rake' in the console."
  end

  task :my_not_default_task do
    puts "This isn't the default task."
  end

However, if you typed rake my_not_default_task, then my_default_task would NOT run. If you want it to run regardless here is one thing you can do:

task :default => 'my_default_task'

task :my_default_task do
    puts "This is the default task"
end

task :my_not_default_task do
  puts "This isn't the default task."
end

Rake::Task['my_default_task'].invoke

The last line in this code ensures that my_default_task runs even when you call some other task, so if you typed rake my_not_default_task the my_default_task'would also run.

EDIT: When you're working with rails you can put the tasks above in a file in the lib/tasks folder with an extension of .rake and rails will automagically run them when you do rake

Jason Seifer has a real nice tutorial on rake.

Upvotes: 2

Related Questions