Summary of the environment for each command.
I found the existing answers to be either incomplete, redundant or not exhaustive. So here is a table format of each command and what the resulting environment looks like.
Rails 7.0
| Command | Rails.const_defined?( "Console" ) | Rails.const_defined?( "Server" ) | ARGV | Rake.application.top_level_tasks |
|------------------------------------|-------------------------------------|-----------------------------------|---------------------------------|----------------------------------|
| `rake db:migrate:status` | false | false | ["db:migrate:status"] | ["db:migrate:status"]
| `rails console` | true | false | [] | []
| `rails server` | false | true | [] | []
| `rails g migration new_migration` | false | false | ["migration", "new_migration"] | []
| `rails r "puts 'Hi'"` | false | false | ["puts 'hi'"] | []
Rails 4.2
| Command | Rails.const_defined?( "Console" ) | Rails.const_defined?( "Server" ) | ARGV |
|------------------------------------|-------------------------------------|------------------------------------|---------------------------------|
| `rake db:migrate:status` | false | true | ["db:migrate:status"] |
| `rails console` | true | true | [] |
| `rails server` | false | true | [] |
| `rails g migration new_migration` | false | true | ["migration", "new_migration"] |
| `rails r "puts 'Hi'"` | false | true | [] |
You can see that just checking for "Server" being defined as a Rails
constant will not catch generators, like rails g migration
. You need to check the ARGV
to do that.
I hope this helps. I only had immediate access to Rails 4.2 but feel free to add sections for other Rails versions, as well as add any additional commands that need "catching".
NOTE: I found in Rails 7 (and maybe in some other version between 4.2 and 7) this changed quite dramatically and a few of our checks were failing because of it, so I updated the answer for Rails 7.0 and had to include a new command Rake.application.top_level_tasks
to make things work on our end again. Hope it helps.