Advanced Rails - Building Industrial-Strength Web Apps in Record Time

(Tuis.) #1

Whiny Nil


60 | Chapter 2: ActiveSupport and RailTies


The JSON library protects against circular references, which cannot be encoded into JSON:
a = {}
b = {:a => a}
a[:b] = b
a # => {:b=>{:a=>{...}}}


a.to_json
# !> ActiveSupport::JSON::CircularReferenceError: object references itself

Whiny Nil whiny_nil.rb


The extensions toNilClassare an ingenious part of ActiveSupport. They are designed to
help trap unexpectednilvalues as early as possible, and to provide more sensible error
messages to the developer whennil is encountered.


Without these extensions, calling one ofArray’s instance methods on an object that
happened to benilwould generate a standardNoMethodErrorifNilClassdid not also
contain the method. This could be frustrating to track down, especially if the method was
called from deep in the framework.


Whiny Nil intercepts thoseNoMethodErrorswithmethod_missingand makes a suggestion
about the type of object the developer may have been expecting (either Array or
ActiveRecord::Base), based on the name of the method called.
nil.sort


!> NoMethodError: You have a nil object when you didn't expect it!


!> You might have expected an instance of Array.


nil.save
# !> NoMethodError: You have a nil object when you didn't expect it!
# !> You might have expected an instance of ActiveRecord::Base.

The Whiny Nil extensions also redefineNilClass#id, which raises an error. Without this
extension,nil.idwould return 4 (Ruby’s immediate representation ofnil, the same as
nil.object_id). This would be confusing when chaining methods together. Under the
Whiny Nil system, this raises a more informative exception:
nil.id


!> RuntimeError: Called id for nil, which would mistakenly be 4 --


!> if you really wanted the id of nil, use object_id


The Whiny Nil system can be turned off in the Rails configuration by settingconfig.whiny_
nils tofalse.


Core Extensions


The Core Extensions are ActiveSupport’s collection of extensions to Ruby’s core
classes and modules. They are basic design patterns solving problems that are
encountered often in Ruby. These methods are one level below the Rails API; they
are the internal functions that Rails uses. However, we describe them here because

Free download pdf