Build Status Code Climate Coverage Status Gem Version

A quick intro to Naught

What's all this now then?

Naught is a toolkit for building Null Objects in Ruby.

What's that supposed to mean?

Null Objects can make your code more confident.

Here's a method that's not very sure of itself.

class Geordi
  def make_it_so(logger=nil)
    logger && "Reversing the flux phase capacitance!"
    logger && "Bounding a tachyon particle beam off of Data's cat!"
    logger && logger.warn "Warning, bogon levels are rising!"

Now, observe as we give it a dash of confidence with the Null Object pattern!

class NullLogger
  def debug(*); end
  def info(*); end
  def warn(*); end
  def error(*); end
  def fatal(*); end

class Geordi
  def make_it_so( "Reversing the flux phase capacitance!" "Bounding a tachyon particle beam off of Data's cat!"
    logger.warn "Warning, bogon levels are rising!"

By providing a NullLogger which implements [some of] the Logger interface as no-op methods, we've gotten rid of those unsightly && operators.

That was simple enough. Why do I need a library for it?

You don't! The Null Object pattern is a very simple one at its core.

And yet here we are…

Yes. While you don't need a Null Object library, this one offers some conveniences you probably won't find elsewhere.

But there's an even more important reason I wrote this library. In the immortal last words of James T. Kirk: "It was… fun!"

OK, so how do I use this thing?

Well, what would you like to do?

I dunno, gimme an object that responds to any message with nil

Sure thing!

require 'naught'

NullObject =

null =                        # => nil                        # => nil

That was… weird. What's with this "build" business?

Naught is a toolkit for building null object classes. It is not a one-size-fits-all solution.

What else can I make for you?

How about a "black hole" null object that supports infinite chaining of methods?


require 'naught'

BlackHole = do |config|

null =                           # => <null>                   # => <null>
null << "hello" << "world"         # => <null>

What's that "config" thing?

That's what you use to customize the generated class to your liking. Internally, Naught uses the Builder Pattern to make this work..

Whatever. What if I want a null object that has conversions to Integer, String, etc. using sensible conversions to "zero values"?

We can do that.

require 'naught'

NullObject = do |config|

null =

null.to_s                          # => ""
null.to_i                          # => 0
null.to_f                          # => 0.0
null.to_a                          # => []
null.to_h                          # => {}
null.to_c                          # => (0+0i)
null.to_r                          # => (0/1)

Ah, but what about implicit conversions such as #to~str~? Like what if I want a null object that implicitly splats the same way as an empty array?

Gotcha covered.

require 'naught'

NullObject = do |config|

null =

null.to_str                     # => ""
null.to_ary                     # => []

a, b, c = []
a                               # => nil
b                               # => nil
c                               # => nil
x, y, z = null
x                               # => nil
y                               # => nil
z                               # => nil

How about a null object that only stubs out the methods from a specific class?

That's what mimic is for.

require 'naught'

NullIO = do |config|
  config.mimic IO

null_io =

null_io << "foo"                # => nil
null_io.readline                # => nil
null_io.foobar                  # => 
# ~> -:11:in `<main>': undefined method `foobar' for 
#  <null:IO>:NullIO (NoMethodError)

There is also impersonate which takes mimic one step further. The generated null class will be derived from the impersonated class. This is handy when refitting legacy code that contains type checks.

require 'naught'

NullIO = do |config|
  config.impersonate IO

null_io =
IO === null_io                  # => true

case null_io
when IO
  puts "Yep, checks out!"
  null_io << "some output"
  raise "Hey, I expected an IO!"
# >> Yep, checks out!

Alright smartypants. What if I want to add my own methods?

Not a problem, just define them in the .build block.

require 'naught'

NullObject = do |config|
  def to_path

  # You can override methods generated by Naught
  def to_s

null =
null.to_s                       # => "NOTHING TO SEE HERE MOVE ALONG"
null.to_path                    # => "/dev/null"

Got anything else up your sleeve?

Well, we can make the null class a singleton, since null objects generally have no state.

require 'naught'

NullObject = do |config|

null = NullObject.instance

null.__id__                     # => 17844080
NullObject.instance.__id__      # => 17844080                  # => 
# ~> -:11:in `<main>': private method `new' called for 
#  NullObject:Class (NoMethodError)

Speaking of null objects with state, we can also enable tracing. This is handy for playing "where'd that null come from?!" Try doing that with nil!

require 'naught'

NullObject = do |config|

null =           # line 7

null.__file__                   # => "example.rb"
null.__line__                   # => 7

We can even conditionally enable either singleton mode (for production) or tracing (for development). Here's an example of using the $DEBUG global variable (set with the -d option to ruby) to choose which one.

require 'naught'

NullObject = do |config|
  if $DEBUG

The only caveat is that when swapping between singleton and non-singleton implementations, you should be careful to always instantiate your null objects with NullObject.get, not .new or .instance. .get will work whether the class is implemented as a singleton or not.

NullObject.get                  # => <null>

Are you done yet?

Just one more thing. For maximum convenience, Naught-generated null classes also come with a full suite of conversion functions which can be included into your classes.

require 'naught'

NullObject =

include NullObject::Conversions

# Convert nil to null objects. Everything else passes through.
Maybe(42)                       # => 42
Maybe(nil)                      # => <null>
Maybe(NullObject.get)           # => <null>
Maybe{ 42 }                     # => 42

# Insist on a non-null (or nil) value
Just(42)                        # => 42
Just(nil) rescue $!             # => #<ArgumentError: Null value: nil>
Just(NullObject.get) rescue $!  # => #<ArgumentError: Null value: <null>>

# nils and nulls become nulls. Everything else is rejected.
Null()                          # => <null>
Null(42) rescue $!              # => #<ArgumentError: 42 is not null!>
Null(nil)                       # => <null>
Null(NullObject.get)            # => <null>

# Convert nulls back to nils. Everything else passes through. Useful
# for preventing null objects from "leaking" into public API return
# values.
Actual(42)                      # => 42
Actual(nil)                     # => nil
Actual(NullObject.get)          # => nil
Actual { 42 }                   # => 42


gem install naught


  • Ruby 1.9


  • Fork, branch, submit PR, blah blah blah. Don't forget tests.

Who's responsible

Naught is by Avdi Grimm.

Prior Art

This isn't the first Ruby Null Object library. Others to check out include:

Further reading