Rails如何检查当前是IRB控制台还是Web页面?

5

在我的模型中,我想检查应用程序是在IRB控制台中运行还是作为网站运行?

class MyModel < ActiveRecord::Base
  def xmethod
    if !isIRBconsol
      self.user_id = UserSession.find.user.id
    end
  end
end

3
为什么你想要这个?可能还有更好的解决方案来解决更大的问题。 - Kathy Van Stone
我想在 before_save 之前设置模型的 user_id 字段。因为 UserSession 在 IRB 中不存在,所以我尝试了类似的东西。有更好的解决方案吗? - xpepermint
3个回答

4
为什么不直接使用if defined?(IRB)

2
这似乎并不总是有效,取决于您的范围,我现在已经选择了Rails.const_defined?('Console') - toupeira

3
这是一个有点儿巧妙的方法,但应该能够实现:
class MyModel < ActiveRecord::Base
  def am_i_in_irb?
    self.private_methods.include? 'irb_binding'
  end
end

但正如Kathy Van Stone所说,这可能有更好的解决方案。

0
unless self.private_methods.include? 'irb_binding'
   #put your rufus scheduling here
end

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接