How to get name of current rake task in my Rails model?
Asked Answered
C

3

10

I have some problems with one of gem supporting ActiveModel caching. 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. 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. How to check it?

Christy answered 30/5, 2012 at 9:53 Comment(1)
"one of gem supporting ActiveModel caching" - which one?Clovah
I
1

If you run your task via rake task or bundle exec rake task you can check it in your initializer simply by:

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

You can use $PROGRAM_NAME instead of $0 if you like.

Isom answered 30/5, 2012 at 11:54 Comment(1)
FYI, this doesn't work in Rails 7.1. $PROGRAM_NAME #=> "bin/rails"Speedwell
S
18

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
Seabolt answered 30/5, 2012 at 11:35 Comment(2)
If you have namespaced tasks, this should work puts task_name.name.split(':').last (in rake v10.4.2).Harriettharrietta
Doesn't show how to get the task name in a "Rails model" as the question asks.Denticulation
T
13

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 doesn't necessarily run just one task.

Tann answered 26/6, 2013 at 19:54 Comment(2)
Yup, the question asked about getting the name and the selected answer shows how to detect if you're in a rake task. This is the right answer.Kierkegaardian
I think this is more elegant than adding do |task name|.Teodoor
I
1

If you run your task via rake task or bundle exec rake task you can check it in your initializer simply by:

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

You can use $PROGRAM_NAME instead of $0 if you like.

Isom answered 30/5, 2012 at 11:54 Comment(1)
FYI, this doesn't work in Rails 7.1. $PROGRAM_NAME #=> "bin/rails"Speedwell

© 2022 - 2024 — McMap. All rights reserved.