How can I detect if my code is running in the console in Rails 3?
Asked Answered
C

2

43

I have this code in an initializer:

if $0 == 'irb'
  # ...
end

It works fine with Rails 2.3 but in Rails 3 the value of $0 is 'script/rails' no matter if it was started with rails c or rails s. ARGV is an empty array. How can I detect if the application has been started with "rails c" or "rails console"?

Choreographer answered 5/1, 2011 at 11:50 Comment(0)
K
83

You could try this perhaps

if defined?(Rails::Console)
  # in Rails Console
else
  # Not in Rails Console
end
Kaila answered 5/1, 2011 at 12:42 Comment(7)
Note that this won't work during Rails initialization when running Spring.Jeanmariejeanna
You want Rails.const_defined?("Console"), not defined?(Rails::Console).Rufford
@Rufford why is that better?Surveyor
@AndreasStorvikStrauman Rails::Console is not defined in all contexts and configurations. When it's not, you'll get a NameError. Rails.const_defined?("Console") is safe so long as Rails is defined.Rufford
@Rufford @Andreas defined? is a special method and will let you pass whatever name you want, e.g. defined?(Hwddddw::Ewedw) # => nilCelibate
@Celibate - whoa my bad! Apologies. I got an error when I first used Aditya's original formulation, and assumed it was as I reported above. Thanks for the correction.Rufford
unless i'm missing something, this is not working anymore in rails 6. https://mcmap.net/q/379373/-how-can-i-detect-if-my-code-is-running-in-the-console-in-rails-3 is working.Elianore
R
8

Many years later there is a better method to do this registering blocks to run for the console (using the railtie interface).

So in the initializer you can write:

Rails.application.console do
  # your code here
end

The good think about this is that it also works for runner and it should also work with spring (but I didn't test that).

Romanism answered 16/8, 2019 at 14:9 Comment(6)
works for me in rails 6, unlike ` defined?(Rails::Console)`Elianore
Works in initialization with spring. Just what I was looking for.Meperidine
Is there something related to this solution that facilitates conditionally doing something in config.after_initialize only when not using a console? That's my use case.Clash
@Clash defined?(Rails::Console) works for me in this context.Smallsword
@Clash had asked -- "is there a way to do this when not using a console?" and another option if you just want to run stuff only when it's a rails s then put your code in config.ru.Landeros
Works for me in rails 7Vivica

© 2022 - 2024 — McMap. All rights reserved.