rake icon indicating copy to clipboard operation
rake copied to clipboard

Add a Rake.application.running? predicate

Open leonid-shevtsov opened this issue 7 years ago • 3 comments

I have added a Rake.application.running? method, that returns true if Rake is running currently, and false otherwise. It is most useful to fence off code that is only needed for Rake tasks, or conversely, should not run inside a Rake task.

This is a common need in Rails apps and the most popular way to see if the code is running within a rake task is checking the command line argument (see SO answers at the bottom). Which might work, but it is messy, and leads to copy-paste of the File.basename($0) == 'rake' idiom. Our project uses that code snippet in three distinct places, but instead of fixing this on a project level, in my opinion, it is a capability that Rake should have out of the box.

StackOverflow answers that suggest checking the script filename:

  • https://stackoverflow.com/a/42619194/6678
  • https://stackoverflow.com/a/15767148/6678

leonid-shevtsov avatar Dec 19 '17 09:12 leonid-shevtsov

It is most useful to fence off code that is only needed for Rake tasks, or conversely, should not run inside a Rake task.

Interesting, I haven't had the need like this. Could you elaborate on this?

yuki24 avatar Dec 19 '17 16:12 yuki24

Done - sorry for the huge delay.

To elaborate on this:

It is most useful to fence off code that is only needed for Rake tasks, or conversely, should not run inside a Rake task.

to give one example, we mark changes made from a rake task for audit:

if File.basename($PROGRAM_NAME) == "rake"
  PaperTrail.whodunnit = "#{`whoami`.strip}: rake #{ARGV.join ' '}"
end

Another places I can recall:

  • extended logging inside Rake tasks - logs that would be spammy in the server process.
  • do not start project-specific subsystems that are known to make Rake tasks slow and are not necessary in Rake tasks.

(All of the above assumed a webapp context.)

leonid-shevtsov avatar May 02 '18 09:05 leonid-shevtsov

I'm the author of one of those Stack Overflow questions (many years ago).

I think this is a worthwhile addition to Rake, but I have 1 suggestion and 1 concern:

First, I think it would be simpler to just have it be Rake.running?. Second, to use this, you'd have to check that the Rake constant is defined:

defined?(Rake) && Rake.running?

booch avatar Aug 30 '18 20:08 booch