Using Null Object pattern with Ruby on Rails

While back ago I’ve released plugin to implement Null Object Pattern. And I’ve decided to write about it. Mostly because people are not using it or don’t know it.

What it does?

Instead of using a null reference to convey absence of an object (for instance, a non-existent customer), one uses an object which implements the expected interface, but whose method body is empty. The advantage of this approach over a working default implementation is that a Null Object is very predictable and has no side effects.

Why should I use it?

  • You will not have to prevent your code from having null reference. For example you will not have to do this:
    1
      print post.user.nil? ? 'Null user' : post.user.name

    With Null Object pattern you write just print post.user.name and you’ll get default value for Null object defined for this attribute.

  • It’s very handy if you’re doing some kind of reporting that you don’t have to deal with null reference and you have object (in SQL row reference) instead.

To install the plugin

1
ruby script/plugin install git://github.com/lacomartincik/acts_as_nullobject.git

Let’s have a look how to use it
First you’ll need to define model to acts as null object:

1
2
3
class User < ActiveRecord::Base
  acts_as_nullobject :login => 'lacomartincik', :name => 'Ladislav Martincik'
end

Than whenever you call on User class method null_object you will get instance of NullUser class with default attributes defined in User:

1
2
>> User.null_object
=> NullUser...

Now if you define relationship between say Project and User like this:

1
2
3
class Project < ActiveRecord::Base
   belongs_to_with_nullobject :user
end

Than whenever you create new Project object with null reference to User you will get NullUser instance instead of nil:

1
2
3
>> p = Project.new
>> p.user
=> NullUser

The project is available as plugin on http://github.com/lacomartincik/acts_as_nullobject.

Enjoy! Any suggestions, bug reports and comments welcomed!

Update: I had to rename plugin name from acts-as-nullobject to acts_as_nullobject otherwise it’s not going to work in Rails!

1 Comment so far

  1. Carlos S on March 14th, 2009

    I am not able to use your plugin at all.
    1. How can I install it from github?
    2. I copied it in my vendors/plugins dir, and when I go to console then I get an error: /usr/lib/ruby/gems/1.8/gems/activesupport-2.1.0/lib/active_support/dependencies.rb:492:in `const_missing’:NameError: uninitialized constant Rails::Plugin::Acts.

    Also, please update hyperlinks on this page.

    Thanks,
    CS.

Leave a Reply