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

activemodel, rake, ruby-on-rails

Solution

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.

Problem

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?

Original source