2011-09-26 17 views
5

में नहीं के बराबर विकास मोड में के लिए आईडी:नामक रेल 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

देखो:

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

इस विकास मोड में रहते हुए nil पर तरीकों को कॉल करने से आप को रोकने के लिए है। मुझे लगता है कि उन्होंने इसे उत्पादन में प्रदर्शन कारणों से अक्षम कर दिया है।

और nil रूबी में एक सिंगलटन ऑब्जेक्ट है, यही कारण है कि id 4 चाहे कोई फर्क नहीं पड़ता।

config.whiny_nils = true 

कौन सा एक त्रुटि लॉग इन करें जब आप nil पर एक विधि कॉल करने की कोशिश करेंगे:

+1

इसके अलावा, 'nil.id' == 4, जो अनायास ही दुष्प्रभाव –

+0

@phsr धन्यवाद कारण हो सकता है, जोड़ा सिंगलटन शून्य के बारे में थोड़ा सा –

1

व्हिनी नील केवल विकास मोड के दौरान रिपोर्ट की जाती हैं (अपनी कॉन्फ़िगरेशन फ़ाइलों में देखें)।

"whiny निल्स" लॉग जब भी एक तरीका है (उम्मीद) उपयोगी जानकारी वस्तु का जो प्रकार के बारे में आप की कोशिश कर रहा हो सकता है के साथ एक नहीं के बराबर मूल्य पर शुरू हो जाती है, में चेतावनी डालने के लिए रेल शब्द है उपयोग।

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