None of the other answers presented here will work unless you stop using Spring, because Spring changes the way rake tasks are called significantly.
When using Spring, the command being run is handed over to the Spring server process using a UNIX socket and unfortunately Spring server reads this socket to get the command and its arguments after initializing the rails environment. Thus, during rails initialization, there seems to be no way of getting the command and its arguments (e.g. the rake task name) when using Spring, as Spring itself does not know yet! Even the after_fork
hook that Spring provides won't help, because it is being also run after rails initialization.
A proof can be seen in the Spring source code. It is the serve
method in which Spring gets the ARGV
of the command being run from the socket, forks itself and runs the command. The relevant parts of the method are these:
def serve(client)
# ... getting standard input / output streams from the client socket
# this is where rails initialization occurs
preload unless preloaded?
# this is where Spring gets the command name and it's ARGV and environment
args, env = JSON.load(client.read(client.gets.to_i)).values_at("args", "env")
command = Spring.command(args.shift)
# ...
# fork and run the command
pid = fork {
# ...
# run the command
ARGV.replace(args)
$0 = command.exec_name
# ...
# run the after_fork hook
invoke_after_fork_callbacks
command.call
}
# ...
end
The rails initializers are run in the preload
method which is run before the command name is read from the socket. The $0
and ARGV
variables are also set after initialization, in the fork
block.
So, unless you monkey-patched Spring significantly (replaced the serve
method with your own, but you'd need to handle working with the socket yourself), you need to stop calling your rake tasks inside the Spring environment. If the rake
command is a binstub in the RAILS_ROOT/bin/
directory, you need to remove the binstub with spring binstup --remove rake
.
Only then, I believe, you can use one of the solutions in the other answers.