Nullz 🔮
A Ruby gem for elegantly handling nil values using the Null Object pattern.
Introduction 📖
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.
Installation 🔧
Add this line to your application's Gemfile:
gem 'nullz'And then execute:
bundle install
Or install it yourself as:
gem install nullz
Usage 💡
Methods
-
_(obj): Returnsobjunless 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 aNullObjectis created. -
safe(obj, on_null_object_created_proc = Proc.new {}): Toggles the use ofNullObjectbased on theNullz.use_null_objectconfiguration.
Configuration
Configure Nullz in an initializer or similar:
Nullz.use_null_object = true
Nullz.on_null_object_created = -> { puts "Null object created!" }
NullObject Class
- Represents
nilornull. - This class defines a special kind of object meant to represent
nilornull. - It overrides various methods to return either
nilrepresentations (like into_s,to_i, etc.), or a new instance ofNullObject(in arithmetic and bitwise operations). - It also defines behavior for comparison (
==,!=) withniland handling of unknown methods viamethod_missing. - Special methods like
nil?,null?,empty?are overridden to provide appropriate behavior for anullobject.