开发者

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

开发者 https://www.devze.com 2022-12-23 13:15 出处:网络
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 generat开发者_Python百科or, since it\'s n

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 generat开发者_Python百科or, since it's not useful in those situations. Is there any way to tell if that's the case?


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'


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


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

$0 =~ /rake$/


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.


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


You can disable the plugin using environment variable:

$ DISABLE_BULLET= 1 rake some:task

And then in your code:

unless ENV['DISABLE_BULLET']
end


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号