Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails - execute rake task at initialization

I want to execute two rake tasks which initialise my database when the server starts. Therefore, I placed the following code in config/application.rb:

config.after_initialize do
      Rake::Task[ 'download_csv:get_files' ].invoke
      Rake::Task[ 'download_csv:place_in_database' ].invoke
end

However, I get the following error:

.rvm/rubies/ruby-2.2.1/lib/ruby/2.2.0/rake/task_manager.rb:62:in `[]': Don't know how to build task 'download_csv:get_files' (RuntimeError)

What am I doing incorrectly? (My objective is to initialise the database at startup).

like image 266
octavian Avatar asked May 22 '15 18:05

octavian


2 Answers

Rails tasks are not automatically loaded, you need to load them first:

config.after_initialize do
  Rails.application.load_tasks # <---
  Rake::Task['download_csv:get_files'].invoke
  Rake::Task['download_csv:place_in_database'].invoke
end

Note that #load_tasks doesn't store state and if you call it again somewhere else you can experience problems.

On the other hand, the names of the tasks suggest that they don't need to be run on every web instance (e.g. Heroku Dynos); but they will run on each machine using the above strategy. So if you have scaled your web instances (running your app on more than one machine), running these tasks in a single instance (a one-off Dyno on Heroku) as an automated after-deploy task would be more effective.

like image 152
Halil Özgür Avatar answered Oct 17 '22 08:10

Halil Özgür


download_csv:place_in_database implies there is a task named place_in_database within a namespacedownload_csv. Is this how your Rake task looks? It would be much easier diagnose the problem if you post the code.

Also, ensure that your .rake files reside in lib/tasks.

like image 24
Andy Waite Avatar answered Oct 17 '22 08:10

Andy Waite