35

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?

Craig Buchek
  • 894
  • 1
  • 8
  • 19
  • 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 Answers7

39

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'
Joshua Pinter
  • 45,245
  • 23
  • 243
  • 245
slaxor
  • 531
  • 4
  • 8
9

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
Tilo
  • 33,354
  • 5
  • 79
  • 106
  • 1
    Given 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
6

$0 holds the current ruby program being run, so this should work:

$0 =~ /rake$/
NickMerwin
  • 61
  • 1
  • 2
4

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

Daniel Garmoshka
  • 5,849
  • 39
  • 40
3

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.

Mark Rushakoff
  • 249,864
  • 45
  • 407
  • 398
1

You can disable the plugin using environment variable:

$ DISABLE_BULLET= 1 rake some:task

And then in your code:

unless ENV['DISABLE_BULLET']
end
x-yuri
  • 16,722
  • 15
  • 114
  • 161
1

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.

Hector Zhao
  • 101
  • 1
  • 3