简体   繁体   English

如果我正在运行 rake 命令,如何在 rails 中检测?

[英]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.在 Rails 中,您可能希望您的环境在启动时做不同的事情,这取决于您是否正在运行 rake 任务。 For instance, my use case was having several hundred MB of cache loaded into memory on app start.例如,我的用例是在应用程序启动时将数百 MB 的缓存加载到内存中。 We obviously don't want this to happen on rake commands.我们显然不希望这种情况发生在 rake 命令上。

---update--- The following is reliable solution and works with heroku. ---更新--- 以下是可靠的解决方案,适用于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. 检测您的环境是否在rake命令中非常容易,但是花了我一段时间才弄清楚。 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

Rake.application.top_level_tasks is set by rake to the list of arguments (tasks to be executed): Rake.application.top_level_tasksrake设置为参数列表(要执行的任务):

https://github.com/ruby/rake/blob/v13.0.3/exe/rake#L27 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#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#L97
https://github.com/ruby/rake/blob/v13.0.3/lib/rake/application.rb#L751-L761 https://github.com/ruby/rake/blob/v13.0.3/lib/rake/application.rb#L751-L761

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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