How to inherit from NilClass or how to simulate a similar function

I just want to use the Null Object Design Pattern, but I found that I can inherit NilClass.

I can write the method "nil?" and returns false, but what if the user writes the code below

if null_object puts "shouldn't be here" end 

Follow these steps to find out what I'm trying to do.

 record = DB.find(1) # if it can not find record 1, the bellow code should not raise exception record.one_attr # and what more if record puts "shouldn't be here" end # I don't want to override all NilClass 
+4
source share
3 answers

An approach that might work for you is to override the #nil method? in the null object. Does this mean that in your code you must use obj.nil to check for a null value? and not just check the existence of obj. This is probably reasonable since you can distinguish between nil and null. The following is an example:

 class NullClass def nil? true end def null_behavior puts "Hello from null land" end end 

Inheritance will work:

 class NewClass < NullClass end 

Use like this:

 normal = Class.new null = NewClass.new x = [normal, null] x.each do |obj| if obj.nil? puts "obj is nil" obj.null_behavior end end 

Output:

 obj is nil Hello from null land 

Remember to use # .nil? for any checks that require Null and Nil to be false.

Below this line was my INCORRECT initial answer

 CustomNil = Class.new(NilClass) class CustomNil def self.new ###!!! This returns regular nil, not anything special. end end 

[tests removed for brevity]

Use at your own risk. I have not investigated what side effects this can cause or will do what you want. But it looks like it really has something like nil like

+3
source

I don’t think that Ruby actually allows you to inherit from NilClass and create an object on it:

 class CustomNilClass < NilClass end custom_nil_object = CustomNilClass.new # => NoMethodError: undefined method `new' for CustomNilClass:Class 
0
source

Instead of inheriting from NilClass I do the following

 class NullObject < BasicObject include ::Singleton def method_missing(method, *args, &block) if nil.respond_to? method nil.send method, *args, &block else self end end end 

This gives you any custom method that has been beheaded on NilClass (e.g. ActiveSupport blank? And nil? ). You can also, of course, add custom properties to the null object or change method_missing to handle other calls differently (this returns a NullObject for the chain, but you can return, for example, nil ).

0
source

Source: https://habr.com/ru/post/1342958/


All Articles