Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mongoid association & null object pattern?

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.

like image 634
Yeggeps Avatar asked May 22 '26 09:05

Yeggeps


1 Answers

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.

like image 77
Sergio Tulentsev Avatar answered May 24 '26 01:05

Sergio Tulentsev



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!