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?
-
See this answer to further distinguish between `rake`, `rails c`, `rails s`, `rails g`: https://stackoverflow.com/a/53963584/293280 – Joshua Pinter Dec 28 '18 at 21:31
7 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'

- 45,245
- 23
- 243
- 245

- 531
- 4
- 8
-
This works, but it's ugly, because it depends on Rake internally defining a global variable - which might go away in the future – Tilo Feb 18 '14 at 21:51
-
15In Rails 4, the above didn't work for me, but **if File.basename($0) == 'rake'** still did. – codenoob Mar 02 '14 at 04:07
-
2
-
2It's actually preferred to use `$PROGRAM_NAME` instead of `$0` to be more explicit. – Joshua Pinter Oct 17 '18 at 03:50
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

- 33,354
- 5
- 79
- 106
-
1Given some recent experiences trying to determine if the environment is running within rake, testing $0 is the most reliable. defined?(::Rake) seemed to always be true, at least in Rails, so that did not work. I looked for global variables but did not find anything suitable. – Martin Streicher Mar 31 '14 at 13:26
The most stable option is to add $is_rake = true
at the beginning of Rakefile
and use it from your code.
Use of $0
or $PROGRAM_NAME
sometimes will fail, for example when using spring and checking variables from config/initializers

- 5,849
- 39
- 40
It appears that running rake
will define a global variable $rakefile
, but in my case it gets set to nil
; so you're better off just checking if $rakefile
has been defined... seeing as __FILE__
and $FILENAME
don't get defined to anything special.
$ cat test.rb
puts(global_variables.include? "$rakefile")
puts __FILE__
puts $FILENAME
$ cat Rakefile
task :default do
load 'test.rb'
end
$ ruby test.rb
false
test.rb
-
$ rake
(in /tmp)
true
./test.rb
-
Not sure about script/generator, though.

- 249,864
- 45
- 407
- 398
You can disable the plugin using environment variable:
$ DISABLE_BULLET= 1 rake some:task
And then in your code:
unless ENV['DISABLE_BULLET']
end

- 16,722
- 15
- 114
- 161
We could ask this
Rake.application.top_level_tasks
In a rails application, this is an empty array, whereas in a Rake task, the array has the task name in it.
top_level_tasks
probably isn't a public API, so it's subject to changes. But this is the only thing I have found.

- 101
- 1
- 3