vendredi 8 mai 2020

How to implement "safe navigation"-compatible "null object pattern"?

I like the Null Object Pattern, e.g.

class NullAddress
  def details; "No address entered yet";  end

  def blank?;   true; end
  def present?; false; end
  def nil?;     true; end
end

address = NullAddress.new

But I have no idea (nor found something) how to make this &.-compatible:

address&.city
#=> NoMethodError: undefined method `city' for #<NullAddress:0x000055d3bbdeb7e8>

Unfortunately Safe Navigation is widely used in our application, so I have to keep that in mind when implementing Null Object Pattern.

I've tried with extending NullObject. But this doesn't raise any NoMethodError at all:

address.foo_is_no_method
#=> nil

Any hints?

Aucun commentaire:

Enregistrer un commentaire