2011-09-26 76 views
5

零在發展模式:名爲id爲Rails 3的

nil.id 
=> "Called id for nil, which would mistakenly be 4 -- if you really wanted the id of nil, use object_id" 

在生產模式:

nil.id 
=> 4 

爲什麼?

回答

11

查找行,說你的環境CONFIGS如下:

# Log error messages when you accidentally call methods on nil. 
config.whiny_nils = true # or false in production.rb 

這是爲了防止你打電話,而在發展模式上nil方法。我想他們出於性能原因在生產中禁用了它。

nil是ruby中的單例對象,這就是爲什麼它的id將是4的原因。

+1

另外'nil.id' == 4,這可能會導致不期望的副作用 –

+0

@phsr感謝,添加的有關單身人士零 –

1

只有在開發模式(查看您的配置文件)中才報告Whiny nils。

「嘀咕尼爾斯」是把警告轉化每當方法被調用,在零值,以(希望)有用 關於哪些類型的對象,你可能一直在試圖 日誌 Rails的項使用。

2

方法NilClass#id的代碼具有很好的解釋:

# NilClass#id exists in Ruby 1.8 (though it is deprecated). Since +id+ is a fundamental 
# method of Active Record models NilClass#id is redefined as well to raise a RuntimeError 
# and warn the user. She probably wanted a model database identifier and the 4 
# returned by the original method could result in obscure bugs. 
# 
# The flag <tt>config.whiny_nils</tt> determines whether this feature is enabled. 
# By default it is on in development and test modes, and it is off in production 
# mode. 

https://github.com/rails/rails/blob/0c76eb1106dc82bb0e3cc50498383d6f992da4fb/activesupport/lib/active_support/whiny_nil.rb#L19