简体   繁体   中英

How do I detect in rails if I am running a rake command?

In Rails, you might want your environment to do different things on startup depending on if you are running a rake task or not. For instance, my use case was having several hundred MB of cache loaded into memory on app start. We obviously don't want this to happen on rake commands.

---update--- The following is reliable solution and works with heroku.

is_rake = (ENV['RACK_ENV'].blank? || ENV['RAILS_ENV'].blank? || !("#{ENV.inspect}" =~ /worker/i).blank?)

Detecting if your environment is in a rake command is pretty easy, but, it took me a while to figure it out. I hope this helps someone out there!

#In environment.rb, I do the following
is_rake = !("#{ENV.inspect}" =~ /rake/i).blank?
puts "Is Rake? #{is_rake}"

如果您正在使用 heroku 并且您正在使用工人,那么这里有一种更可靠的方法来进行此检查。

is_rake = (ENV['RACK_ENV'].blank? || ENV['RAILS_ENV'].blank? || !("#{ENV.inspect}" =~ /worker/i).blank?)

To specialcase running migrations I did the following:

if defined?(Rake) \
&& Rake.application.top_level_tasks.grep(/\Adb:migrate(\[[^\]]*\])?\z/).length > 0
  ...
end

Particularly, it covers the case where we're not running rake .

Rake.application.top_level_tasks is set by rake to the list of arguments (tasks to be executed):

https://github.com/ruby/rake/blob/v13.0.3/exe/rake#L27
https://github.com/ruby/rake/blob/v13.0.3/lib/rake/application.rb#L81
https://github.com/ruby/rake/blob/v13.0.3/lib/rake/application.rb#L97
https://github.com/ruby/rake/blob/v13.0.3/lib/rake/application.rb#L751-L761

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM