Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I run Rails/Rake from another directory?

Without cd-ing into the root directory of my Rails application, how can I execute a Rails or Rake command for that application.

I tried:

bundle exec rake my_tasks:do_stuff BUNDLE_GEMFILE=/PATH/TO/RAILS_APP/Gemfile

among other combinations, to no avail.

[Update]

The issue is actually two-fold, bundle doesn't know where the gemfile is and rake doesn't know what to run.

To use Bundler:

BUNDLE_GEMFILE=/PATH/TO/RAILS_APP/Gemfile bundle exec ...

Note that BUNDLE_GEMFILE has to go before 'bundle exec'.

To use Rake:

rake -f /PATH/TO/RAILS_APP/Rakefile my_task:do_stuff

To use Rails console:

????

Have yet to figure out how to enter the Rails console from another directory. Looking at the source, I think it may not be possible, because it eventually does File.join('script','rails') to kick off the rails process.

like image 794
Nejuf Avatar asked Dec 31 '14 01:12

Nejuf


1 Answers

Without you showing the error message you are getting, I'm assuming it has less to do with Bundler than it does Rake. When the rake command is run, it searches for a Rakefile starting in the current directory and traversing up the tree until it finds one. You can override this behavior by explicitly specifying a Rakefile in the options to the rake command. This is done using the -f <RAKEFILE> option.

eg.

bundle exec rake -f /PATH/TO/RAILS_APP/Rakefile my_task:do_stuff

Bear in mind that your Rake tasks have to be "CWD agnostic". Most tasks and scripts are as they tend to get the project directory based on a path relative to a known file in the directory tree. You probably already understand that, but it's worth mentioning in case the tasks are expecting the current working directory to actually be the rails root. That would be a case where running them from outside the project could potentially be dangerous.

like image 50
Bill Doughty Avatar answered Oct 27 '22 00:10

Bill Doughty