How to inherit from NilClass or how to simulate similar function

后端 未结 3 749
梦谈多话
梦谈多话 2021-01-03 09:04

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

I can write a method \"nil?\" and return false but what if user write code be

3条回答
  •  抹茶落季
    2021-01-03 09:44

    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 have been monkey patched onto NilClass (such as ActiveSupport's blank? and nil?). You can also of course add custom null object behaviors, or change method_missing to handle other calls differently (this one returns the NullObject for chaining, but you could return nil for example).

提交回复
热议问题