Phil
Phil

Reputation: 145

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?

Upvotes: 1

Views: 123

Answers (1)

Amit Patel
Amit Patel

Reputation: 15985

Safe navigation operator is part of ruby's grammar. It's not operator which you can implement as method in your code.

If you still want to get rid of NoMethodError then you can use

def method_missing(m, *args, &block)
  nil
end

but this is just a hack.

There can be other consequences of this implementation when you call other methods which you expect theme on address class but because of method_missing you get nil always.

like address.location will return nil which supposed to throw NoMethodError

Upvotes: 1

Related Questions