如何检测代码是否在Rails 3的控制台中运行?

时间:2021-12-21 20:47:20

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"?

它适用于Rails 2.3,但是在Rails 3中,$0的值是“脚本/ Rails”,无论它是从Rails c或Rails开始的。ARGV是一个空数组。如何检测应用程序是使用“rails c”还是“rails控制台”启动的?

1 个解决方案

#1


79  

You could try this perhaps

你可以试试这个

if defined?(Rails::Console)
  # in Rails Console
else
  # Not in Rails Console
end

#1


79  

You could try this perhaps

你可以试试这个

if defined?(Rails::Console)
  # in Rails Console
else
  # Not in Rails Console
end