0.0
No commit activity in last 3 years
No release in over 3 years
Dead simple library to create null objects (objects that respond to all messages)
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
 Dependencies

Development

~> 1.1.2
>= 0
>= 0
~> 2.10.0
 Project Readme

NullObject

Build Status

Dead simple library to create null objects (objects that respond to all messages)

Requirements

  • MRI 1.9, JRuby in 1.9 mode (JRUBY_OPTS=--1.9), Rubinius in 1.9 mode (RBXOPT=-X19)

Why?

Imagine that sometimes your code uses a statsd client to instrument itself. But only sometimes.

If you used nil to represent the case where the statsd client isn't configured, you end up writing code like this ... which sucks:

statsd.increment("foo") if statsd

And how to you deal with timers? I have no idea

# statsd might be nil, ugh!
statsd.time("foo") { ... }

But if your statsd were either a real Statsd client or a NullObject, the problems go away:

statsd = NullObject.new { |&block| block.call if block }

statsd.increment("foo")    # no need for a conditional; it's a no-op
statsd.time("foo") { ... } # yields to the block, but otherwise a no-op

Usage

Respond to ALL the things:

obj = NullObject.new
obj.foo     # => obj
obj.bar     # => obj
obj.foo.bar # => obj

Yield ALL the things:

obj = NullObject.new { |&block| block.call if block }
obj.foo { puts "bar" } # outputs "bar"

Respond to SOME of the things:

obj = NullObject.new(:foo, :bar)
obj.foo # => obj
obj.bar # => obj
obj.baz # raises NoMethodError

Respond to SOME of the things with CERTAIN return values:

obj = NullObject.new(:foo => :bar)
obj.foo # => :bar
obj.baz # raises NoMethodError

Respond to ALL of the things with a CERTAIN return value:

obj = NullObject.new { "foo" }
obj.foo # => "foo"
obj.bar # => "foo"

Respond to ALL of the things with nil:

obj = NullObject.new { nil }
obj.foo # => nil

Contributing

  1. Fork it
  2. Create your feature branch (git checkout -b my-new-feature)
  3. Commit your changes (git commit -am 'Added some feature')
  4. Push to the branch (git push origin my-new-feature)
  5. Create new Pull Request