Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Force Rake Task To Run in Specific Rails Environment

I need to run a series of Rake tasks from another Rake task. The first three tasks need to be run in the development environment, but the final task needs to be run in the staging environment. The task has a dependency on :environment which causes the Rails development environment to be loaded before the tasks run.

However, I need the final task to be executed in the staging environment.

Passing a RAILS_ENV=staging flag before invoking the rake task is no good as the environment has already loaded at this point and all this will do is set the flag, not load the staging environment.

Is there a way I can force a rake task in a specific environment?

like image 339
Undistraction Avatar asked Feb 04 '14 13:02

Undistraction


People also ask

Why we use Rake task in rails?

Rake is a popular task runner for Ruby and Rails applications. For example, Rails provides the predefined Rake tasks for creating databases, running migrations, and performing tests. You can also create custom tasks to automate specific actions - run code analysis tools, backup databases, and so on.

What does rake environment do?

Including => :environment will tell Rake to load full the application environment, giving the relevant task access to things like classes, helpers, etc. Without the :environment , you won't have access to any of those extras.

What is rakefile in Ruby?

Rake is a tool you can use with Ruby projects. It allows you to use ruby code to define "tasks" that can be run in the command line. Rake can be downloaded and included in ruby projects as a ruby gem. Once installed, you define tasks in a file named "Rakefile" that you add to your project.


1 Answers

I've accomplished this kind of this before, albeit not in the most elegant of ways:

task :prepare do   system("bundle exec rake ... RAILS_ENV=development")         system("bundle exec rake ... RAILS_ENV=development")   system("bundle exec rake ... RAILS_ENV=test")   system("bundle exec rake ... RAILS_ENV=test")   system("bundle exec rake ... RAILS_ENV=test")   system("bundle exec rake ... RAILS_ENV=test") end 

It's always worked for me. I'd be curious to know if there was a better way.

like image 197
kddeisz Avatar answered Sep 22 '22 02:09

kddeisz