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

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

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.


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'

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

$0 =~ /rake$/