Wednesday, July 23, 2014

Simple NullObject For Ruby

Sometimes you don't need something fancy

I love the Null Object pattern. Especially on the things I've been working on where it just needs to work despite errors in data. When you find these errors it's handy to grab a NullObject that will quack like you need. 

Avdi Grimm wrote a great library, naught. It's great when you have a lot of dependency injection. If you're only using it once or twice in your small library, it's probably overkill.

So here's a simple formula for putting in your own simple nullobjects.

class NullObject
  # You can instantiate a new NullObject with arbitrary methods by calling

  # Interactions.NullObject.new({method1: "outcome1"})

  # That will apply the method to the object

  def initialize(methods={})

    methods.each_pair do |k,v|

      define_singleton_method k do

        v

      end

    end

  end

end

Then all you have to do to call it is:

NullObject.new(method1: "Output")

And the key is the method name and the value is whatever you want it to output.
So something like:

def user
  creator || NullObject.new(name: "Jim", accounts: [])
end

Will let your nullobject do user.accounts and return an empty array. Yay you always get an array instead of a NilClass error.

No comments: