3

How would you implement the null object pattern on a Mongoid relation?

Class Owner
  include Mongoid::Document
  embeds_one :preference
end

Most owners won't have a preference, and thus I want them to have a NullPreference instead, as described in Ben Orenstein's excellent talk.

What I would like is something like this:

class NullPreference
  def name
    'no name'
  end 
end

owner = Owner.new
preference = owner.preference
preference.name
=> 'no name' 

I found a related question regarding the same thing in ActiveRecord, no answers though.

Edit: I'm using Mongoid 2.6 otherwise I could've used autobuild: true and get a real Preference and use the defaults instead.

Community
  • 1
  • 1
Yeggeps
  • 2,055
  • 2
  • 25
  • 34

1 Answers1

2

An obvious way is to build a layer of abstraction over that field.

class Owner
  include Mongoid::Document
  embeds_one :preference_field # internal field, don't use directly

  def preference
    preference_field || NullPreference.new
  end

  def preference= pref
    self.preference_field = pref
  end
end

Maybe there are simpler ways.

Sergio Tulentsev
  • 226,338
  • 43
  • 373
  • 367