codahale.com٭blog

Coda Hale lives in Berkeley, CA, where he writes about Ruby on Rails, usability, web design and development, and the occasional bit about bicycles.

NilClass, Devourer Of Errors

Update: This behavior was removed from ruby2ruby 1.1.8 — upgrade and make sure your code works.

From #sequel

[4:03pm] apeiros: ciconia, does sequel add a method_missing that swallows all to NilClass?
[4:05pm] codahale: I think it does.
[4:05pm] codahale: Yeah, it does.
[4:07pm] codahale: I'd seen that behavior in some of my specs -- wasn't sure where it was coming from.
[4:15pm] codahale: Actually, that's in ruby2ruby.
[4:16pm] codahale: Yeah, line #8 in ruby2ruby.rb.
[4:18pm] codahale: apeiros: Is the NilClass#method_missing a real problem for you, or just an unexpected quirk?
[4:19pm] apeiros: it's a real problem
[4:19pm] apeiros: it's a bugkiller
[4:19pm] apeiros: or better said: a debugging/bugfinding killer
[4:20pm] apeiros: an unexpected nil is carried on far far longer than it should and normally would. makes debugging PITA.

Lines 8-12 of ruby2ruby.rb

class NilClass # Objective-C trick
  def method_missing(msg, *args, &block)
    nil
  end
end

An experiment:

>> nil.why_god_why
NoMethodError: undefined method `why_god_why' for nil:NilClass
	from (irb):1
>> require 'ruby2ruby'
=> true
>> nil.why_god_why
=> nil
>> @no_se_existe.please_to_be_raising_error_now
=> nil

Just so’s you know.

3 comments »