A Ruby gem for elegantly handling nil
values using the Null Object pattern.
Nullz
provides a robust way to deal with nil
values in Ruby. Instead of scattering nil
checks throughout your code, Nullz
allows you to handle these cases more gracefully with the NullObject
pattern. This makes your code cleaner, more readable, and less prone to errors.
Add this line to your application's Gemfile:
gem 'nullz'
And then execute:
bundle install
Or install it yourself as:
gem install nullz
-
_(obj)
: Returnsobj
unless it'snil
, in which case it returns aNullz::NullObject
. -
__(obj, on_null_object_created_proc = Proc.new {})
: Similar to_
, but also allows for a custom procedure when aNullObject
is created. -
safe(obj, on_null_object_created_proc = Proc.new {})
: Toggles the use ofNullObject
based on theNullz.use_null_object
configuration.
Configure Nullz
in an initializer or similar:
Nullz.use_null_object = true
Nullz.on_null_object_created = -> { puts "Null object created!" }
- Represents
nil
ornull
. - This class defines a special kind of object meant to represent
nil
ornull
. - It overrides various methods to return either
nil
representations (like into_s
,to_i
, etc.), or a new instance ofNullObject
(in arithmetic and bitwise operations). - It also defines behavior for comparison (
==
,!=
) withnil
and handling of unknown methods viamethod_missing
. - Special methods like
nil?
,null?
,empty?
are overridden to provide appropriate behavior for anull
object.