• Stars
    star
    1,049
  • Rank 43,923 (Top 0.9 %)
  • Language
    Ruby
  • License
    MIT License
  • Created over 11 years ago
  • Updated about 7 years ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

A toolkit for building Null Object classes in Ruby

Gem Version Build Status Dependency Status Code Climate Coverage Status Inline docs

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 && 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!

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!

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.

require 'naught'

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

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

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.

require 'naught'

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

null_io = NullIO.new

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 = 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 << "some output"
else
  raise "Hey, I expected an IO!"
end
# >> 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).

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 predicate methods? You know, the ones that end with question marks? Shouldn't they return false instead of nil?

Sure, if you'd like.

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.

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.

require 'naught'

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

null = NullObject.instance

null.__id__                     # => 17844080
NullObject.instance.__id__      # => 17844080
NullObject.new                  # =>
# ~> -: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 = 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.

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.

NullObject.get                  # => <null>

And if I want to know legacy code better?

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

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.

null = NullObject.new

class MyConsumer < Struct.new(:producer)
  def consume
    producer.produce
  end
end

MyConsumer.new(null).consume
# >> produce() from consume
# => <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 = Naught.build

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

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.

Prior Art

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

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

Libraries Using Naught

  • ActiveNull Null Model support for ActiveRecord.
  • Twitter A Ruby interface to the Twitter API.

More Repositories

1

quarto

Ruby
469
star
2

sbpprb

Smalltalk Best Practice Patterns in Ruby
Ruby
456
star
3

dotenv_elixir

A port of dotenv to Elixir
Elixir
226
star
4

ppwm

A site to promote diverse pair-programming
CSS
223
star
5

hammertime

Exception debugging console for Ruby
Ruby
208
star
6

greenletters

Ruby console automation a la Expect
Ruby
116
star
7

alter-ego

Avdi's personal fork of AlterEgo
Ruby
58
star
8

.emacs24.d

A from-scratch rebuild of my Emacs configuration
Emacs Lisp
46
star
9

cowsay

Enter the cow, baby!
Ruby
41
star
10

firetower

A command-line interface to Campfire chats
Ruby
39
star
11

keyword_params

Declarative Keyword Paramaters for Ruby
Ruby
34
star
12

orgpress

A collection of Makefiles and scripts for generating formatted eBooks.
Ruby
34
star
13

nulldb

NOTE: This is no longer the official Github home of NullDB.
Ruby
32
star
14

leadlight

Rose colored stained glass windows for HTTP
Ruby
30
star
15

rpcfn-interactive-fiction

Ruby Programming Challenge for Newbies: Interactive Fiction
Ruby
28
star
16

brainguy

Ruby
27
star
17

Xcast

Ruby
26
star
18

hookr

A publish/subscribe callback hook facility for Ruby.
Ruby
19
star
19

cow

Ruby
19
star
20

org-rtm

Emacs org-mode/Remember the Milk Integration
Emacs Lisp
19
star
21

lockstep

Ruby
18
star
22

refactoring-in-ruby

My notebook as I work through the exercises in Refactoring in Ruby
15
star
23

gem-love

Show your love for your favorite gems
Ruby
13
star
24

fp_oo_elx

Elixir
13
star
25

walrus

Shell
12
star
26

fail-fast

Avdi's personal fork of FailFast
JavaScript
11
star
27

dm-google-sheet-adapter

DataMappr adapter for Google Sheet
Ruby
9
star
28

tapas-queue

A thread-safe, optionally bounded, timeout-capable queue based on RubyTapas episodes 137-143 (and a few others).
Ruby
8
star
29

gem-isntall

Ruby
7
star
30

tapas-dotfiles

Emacs Lisp
6
star
31

spartan

Butt-naked Ruby tests.
Ruby
6
star
32

handcar

Debugging utility for Rails
Ruby
5
star
33

clafamatt

CLAss FAMily ATTributes gives your classes class-inheritable attributes without all that tedious mucking about with @inheritable_attributes
Ruby
5
star
34

curator

A system for managing all of your digital artifacts
Ruby
5
star
35

mythbashers

JavaScript
4
star
36

feedupdater

Bob "sporkmonger" Aman's Feed Updater Utility
Ruby
4
star
37

gilded_rose_kata

Ruby
4
star
38

preen

Ruby
3
star
39

aws-sam

Playing around with AWS SAM
Python
3
star
40

bewarethemoose

Beware of the Moose
Shell
3
star
41

rack-stereoscope

TODO: one-line summary of your gem
Ruby
3
star
42

zero-zero

An ejection seat for Ruby apps
Ruby
3
star
43

polyglop

POLYglot Grand Language Omniscience Project
Ruby
3
star
44

hookah

Ruby
3
star
45

http_client

A replacement for net/http
Ruby
3
star
46

raffle

Ruby
3
star
47

rack_base_uri

A Rack middleware for automatically setting [X]HTML document base URIs.
Ruby
2
star
48

rudyard

Ruby Refactoring Framework
2
star
49

gem-lovefest

The server side of gem-love
Ruby
2
star
50

lmcr

The example code for Let's Make a Chatbot in Ruby
Ruby
2
star
51

favo5

Ruby
2
star
52

tick

Ruby
2
star
53

dacs

Devver Application Configuration System
Ruby
2
star
54

webscripts

1
star
55

odin

A project for learning TypeScript
TypeScript
1
star
56

rake-server

An experiment at turning Rake into a task server
Ruby
1
star
57

methodical

Automation framework for sequential operations
Ruby
1
star
58

daemon-herder

Ruby
1
star
59

flock-block

Block helper for file locking
Ruby
1
star
60

prototypes-in-ruby

Ruby
1
star
61

pulse-ffi

Ruby
1
star
62

tapas_shot_renumber

A tool for renumbering shots in RubyTapas-style scripts
Dockerfile
1
star
63

rails-synctest

Temporary
Ruby
1
star
64

articles

1
star
65

funwithgit

1
star
66

rut

Ruby
1
star