2011-09-26 2 views
5

에서 전무에 대한 ID를 호출 :개발 모드에서 레일 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 

이유는 무엇입니까? 당신의 환경에 CONFIGS에 다음을 말한다 라인

답변

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 nils는 개발 모드 (구성 파일을보십시오)에서만보고됩니다.

"힘들어 NILS는"방법은 당신이 위해 노력 해왔다 수있는 개체의 어떤 종류에 대해 (희망) 도움이 정보와 더불어, 전무 값에 호출 될 때마다 로그 에 경고를 착용하는 레일 용어입니다 용도.

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

관련 문제