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

后端 未结 2 433
生来不讨喜
生来不讨喜 2020-12-24 11:01

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/ra

相关标签:
2条回答
  • 2020-12-24 11:38

    You could try this perhaps

    if defined?(Rails::Console)
      # in Rails Console
    else
      # Not in Rails Console
    end
    
    0 讨论(0)
  • 2020-12-24 11:41

    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).

    0 讨论(0)
提交回复
热议问题