public
Description: MrProper provides a method for NilClass that avoids raising errors when calling blocks upon it.
Homepage: http://blog.teambox.com/mrproper-cleaner-blocks-in-ruby/
Clone URL: git://github.com/michokest/mrproper.git
Pablo Villalba (author)
Wed Oct 28 12:51:57 -0700 2009
name age message
file README.textile Wed Oct 28 12:49:15 -0700 2009 first commit [Pablo Villalba]
file mrproper.rb Wed Oct 28 12:51:57 -0700 2009 Adding comments [Pablo Villalba]
README.textile

MrProper

MrProper provides a method for NilClass that avoids raising errors when calling blocks upon it.

It defines the function is_defined, which returns self for Enumerable and [] for NilClass.

Came up with this idea when developing Teambox, an open source project management and collaboration tool available at http://www.teambox.com

Example

The following code would raise an exception, because nil.each does not exist:

params[:suscribers] = nil
params[:suscribers].each do |suscriber|
Emailer.deliver_notification suscriber
end

So you would normally need to do the following to avoid it:

params[:suscribers] = nil
if params[:suscribers]
params[:suscribers].each do |suscriber|
Emailer.deliver_notification suscriber
end
end

By using is_defined, the previous code would look like this:

params[:suscribers] = nil
params[:suscribers].is_defined.each do |suscriber|
Emailer.deliver_notification suscriber
end

Installation

Just copy mrproper.rb into config/initializers/mrproper.rb (Ruby on Rails) or any other place where it will get loaded by your app.

Copyright © 2009 Pablo Villalba, released under the MIT license