Baike.dev
All toolsOnline toolsAI codingTrendingOpen sourceNewsSubmit
Log in
< Back to tools
N

naught

> 编程语言
Open source

A toolkit for building Null Object classes in Ruby

1.1K stars0 likes3 views
WebsiteGitHub

About

A toolkit for building Null Object classes in Ruby

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.

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

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

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

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

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!

ruby
require "naught"

NullObject = Naught.build

null = NullObject.new
null.foo                        # => nil
null.bar                        # => 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?

OK.

ruby
require "naught"

BlackHole = Naught.build do |config|
  config.black_hole
end

null = BlackHole.new
null.foo                           # => 
null.foo.bar.baz                   # => 
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.

ruby
require "naught"

NullObject = Naught.build do |config|
  config.define_explicit_conversions
end

null = NullObject.new

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.

ruby
require "naught"

NullObject = Naught.build do |config|
  config.define_implicit_conversions
end

null = NullObject.new

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.

ruby
require "naught"

NullIO = Naught.build do |config|
  config.mimic IO
end

null_io = NullIO.new

null_io  nil
null_io.readline                # => nil
null_io.foobar                  # =>
# ~> -:11:in `': undefined method `foobar' for
#  :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.

ruby
require "naught"

NullIO = Naught.build do |config|
  config.impersonate IO
end

null_io = NullIO.new
IO === null_io                  # => true

case null_io
when IO
  puts "Yep, checks out!"
  null_io > Yep, checks out!

My objects are unique and special snowflakes, with new methods added to them at runtime. How are you gonna mimic that, hotshot?

So long as you can create an object to serve as an example, Naught can copy the interface of that object (both the methods defined by its class, and its singleton methods).

ruby
require "naught"
require "logging"

log = Logging.logger["test"]
log.info

NullLog = Naught.build do |config|
  config.mimic example: log
end

null_log = NullLog.new
null_log.info                  # => nil

What about objects that define methods dynamically, like Stripe API resources?

When you use mimic example:, Naught automatically discovers dynamically-defined methods too. This works with libraries like Stripe that use method_missing to define methods based on API response data.

ruby
require "naught"
require "stripe"

invoice = Stripe::Invoice.retrieve("inv_123")

NullInvoice = Naught.build do |config|
  config.mimic example: invoice
end

null_invoice = NullInvoice.new
null_invoice.period_end        # => nil
null_invoice.amount_due        # => nil
null_invoice.customer          # => nil

Naught discovers dynamic methods by checking if the example object responds to keys, attribute_names, or to_h. If you want to disable this behavior, pass include_dynamic: false:

ruby
NullInvoice = Naught.build do |config|
  config.mimic example: invoice, include_dynamic: false
end

What about predicate methods? You know, the ones that end with question marks? Shouldn't they return false instead of nil?

Sure, if you'd like.

ruby
require "naught"

NullObject = Naught.build do |config|
  config.predicates_return false
end

null = NullObject.new
null.foo                        # => nil
null.bar?                       # => false
null.nil?                       # => false

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

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

ruby
require "naught"

NullObject = Naught.build do |config|
  config.define_explicit_conversions
  config.predicates_return false
  def to_path
    "/dev/null"
  end

  # You can override methods generated by Naught
  def to_s
    "NOTHING TO SEE HERE MOVE ALONG"
  end

  def nil?
    true
  end
end

null = NullObject.new
null.to_path                    # => "/dev/null"
null.to_s                       # => "NOTHING TO SEE HERE MOVE ALONG"
null.nil?                       # => true

Got anything else up your sleeve?

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

ruby
require "naught"

NullObject = Naught.build do |config|
  config.singleton
end

null = NullObject.instance

null.__id__                     # => 17844080
NullObject.instance.__id__      # => 17844080
NullObject.new                  # =>
# ~> -:11:in `': 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!

ruby
require "naught"

NullObject = Naught.build do |config|
  config.traceable
end

null = NullObject.new           # 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.

ruby
require "naught"

NullObject = Naught.build do |config|
  if $DEBUG
    config.traceable
  else
    config.singleton
  end
end

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.

ruby
NullObject.get                  # => 

What if I want to track every method call made on the null object?

Use the callstack configuration to record all method calls, including arguments and source location. This is helpful for debugging when you need to understand exactly how a null object is being used.

ruby
require "naught"

NullObject = Naught.build do |config|
  config.callstack
end

null = NullObject.new
null.foo(1, 2).bar
null.baz

null.__call_trace__
# => [
#      [#,
#       #],
#      [#]
#    ]

Each trace represents a chain of method calls. The CallLocation objects provide access to the method name (label), arguments (args), file path (path), and line number (lineno).

What about safely chaining methods that might return nil?

The null_safe_proxy configuration adds a NullSafe() conversion function that wraps values in a proxy. If any method in a chain returns nil, it gets replaced with a null object, allowing the chain to continue safely.

ruby
require "naught"

NullObject = Naught.build do |config|
  config.null_safe_proxy
end

include NullObject::Conversions

user = nil
NullSafe(user).name.upcase      # => 

user = OpenStruct.new(name: nil)
NullSafe(user).name.upcase      # => 

user = OpenStruct.new(name: "Bob")
NullSafe(user).name.upcase      # => "BOB"

And if I want to know legacy code better?

Naught can make a null object behave as a pebble object.

ruby
require "naught"

NullObject = Naught.build do |config|
  if $DEBUG
    config.pebble
  else
    config.black_hole
  end
end

Now you can pass the pebble object to your code and see which messages are sent to the pebble.

ruby
null = NullObject.new

class MyConsumer > produce() from consume
# => 

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.

…

Installation

gem install naught

Requirements

  • Ruby

Contributing

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

Who's responsible

Naught is by Avdi Grimm and maintained by Erik Berlin.

Prior Art

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

  • NullAndVoid
  • BlankSlate

The Book

If you've read this far, you might be interested in the short ebook, Much Ado About Naught, I (Avdi) wrote as I developed this library. It's a fun exploration of Ruby metaprogramming techniques as applied to writing a Ruby gem. You can read the introduction here.

Further reading

  • [Null Object: Something for Nothing](http://www.

Issues· 0 open

View all issuesOpen on GitHub

No open issues yet, or sync has not completed.

> Tags

Ruby

No comments yet. Be the first to share.

> Details

PublishedAug 1, 2026
UpdatedSep 17, 2026
Category编程语言
PricingOpen source

> Related tools

T
TypeScript
JavaScript 的超集,为前端与全栈提供静态类型
P
Python
通用编程语言,广泛用于 Web、数据与 AI
G
Go
Google 推出的简洁高效系统语言