NullObject
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 statsdAnd 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 # => objYield 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 NoMethodErrorRespond to SOME of the things with CERTAIN return values:
obj = NullObject.new(:foo => :bar)
obj.foo # => :bar
obj.baz # raises NoMethodErrorRespond 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 # => nilContributing
- Fork it
- Create your feature branch (
git checkout -b my-new-feature) - Commit your changes (
git commit -am 'Added some feature') - Push to the branch (
git push origin my-new-feature) - Create new Pull Request