简体   繁体   English

如何在我的Rails模型中获取当前rake任务的名称?

[英]How to get name of current rake task in my Rails model?

I have some problems with one of gem supporting ActiveModel caching. 我有一个支持ActiveModel缓存的gem有问题。 When I'm using observer for cached model, during application initialization it tries to describe table to get all fields names. 当我使用观察者缓存模型时,在应用程序初始化期间,它会尝试描述表以获取所有字段名称。

The same thing is done when rake task is running, including db:migration. rake任务运行时也会执行相同的操作,包括db:migration。 In that case there is some circular reference error. 在这种情况下,存在一些循环引用错误。 I'd like to detect current rake task, to skip gem initialization, but I don't know how to find out was code invoked through rake task. 我想检测当前的rake任务,跳过gem初始化,但我不知道如何找出通过rake任务调用的代码。 How to check it? 怎么检查?

I dont get exactly what you are trying to do, but here is an example of getting the task name. 我没有得到你想要做的,但这里是获取任务名称的一个例子。

  task :testing do |task_name|
    puts task_name
  end

This question has been asked a few places, and I didn't think any of the answers were very good... I think the answer is to check Rake.application.top_level_tasks , which is a list of tasks that will be run. 这个问题已被问到一些地方,我不认为任何答案都非常好...... 认为答案是检查Rake.application.top_level_tasks ,这是一个将要运行的任务列表。 Rake doesn't necessarily run just one task. Rake并不一定只运行一项任务。

If you run your task via rake task or bundle exec rake task you can check it in your initializer simply by: 如果您通过rake taskbundle exec rake task运行任务,您只需通过以下方式在初始化程序中检查它:

if $0.end_with?('rake')
  # rake stuff
else
  # non-rake stuff
end

You can use $PROGRAM_NAME instead of $0 if you like. 如果您愿意,可以使用$PROGRAM_NAME代替$0

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

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