Rails - execute rake command on initialization

I want to do two rake tasks that initialize my database when the server starts up. So I put 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 am getting 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 wrong? (My goal is to initialize the database on startup).

+3


source to share


2 answers


Rails tasks are not loaded automatically, 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 it #load_tasks

does not save state, and if you call it again elsewhere, you may run into problems.

On the other hand, task names suggest that they do not need to be run on every web instance (e.g. Heroku Dynos); but they will work on every machine using the above strategy. So if you scaled your web instances (running your application on multiple machines), doing these tasks in one instance (one-off Dyno on Heroku) as an automated task after deployment would be more efficient.

+5


source


download_csv:place_in_database

it is assumed that download_csv

there is a task named in the namespace place_in_database

. Is this what your Rake task looks like? It would be much easier to diagnose the problem if you posted the code.



Also, make sure your files .rake

are in lib/tasks

.

+1


source







All Articles