Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I tell if Rails code is being run via rake or script/generate?

I've got a plugin that is a bit heavy-weight. (Bullet, configured with Growl notifications.) I'd like to not enable it if I'm just running a rake task or a generator, since it's not useful in those situations. Is there any way to tell if that's the case?

like image 693
Craig Buchek Avatar asked Mar 18 '10 02:03

Craig Buchek


People also ask

What is the rake 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.

Where are Rake tasks located?

rake extension and are placed in Rails. root/lib/tasks . You can create these custom rake tasks with the bin/rails generate task command. If your need to interact with your application models, perform database queries and so on, your task should depend on the environment task, which will load your application code.

What is rake command?

Rake is a Domain Specific Language (DSL), which means you can only use it for things related to Ruby. Rake allows one to write tasks in the Ruby language and execute them on the command line.


2 Answers

It's as simple as that:

if $rails_rake_task   puts 'Guess what, I`m running from Rake' else   puts 'No; this is not a Rake task' end 

Rails 4+

Instead of $rails_rake_task, use:

File.basename($0) == 'rake' 
like image 92
slaxor Avatar answered Sep 23 '22 03:09

slaxor


I like NickMervin's answer better, because it does not depend on the internal implementation of Rake (e.g. on Rake's global variable).

This is even better - no regexp needed

  File.split($0).last == 'rake' 

File.split() is needed, because somebody could start rake with it's full path, e.g.:

  /usr/local/bin/rake taskname 
like image 32
Tilo Avatar answered Sep 23 '22 03:09

Tilo