Class: Cygnet::NullObject

Inherits:
Object
  • Object
show all
Defined in:
lib/cygnet/null_object.rb

Overview

NullObject implements the widely-known NullObject pattern, where an instance responds to any method called on it by returning another NullObject, allowing arbitrary chaining of method calls without the risk of a NoMethodError.

As an exception, NullObject can be cast to other types, taking a neutral value of that type; it is cast to the empty string, 0, 0.0, the empty Array and Hash, etc.

Additionally, it identifies positively as #nil? and #blank? for compatability with common checks on “neutral” or “empty” values by imitating the behaviour of nil.

Instance Method Summary collapse

Dynamic Method Handling

This class handles dynamic methods through the method_missing method

#method_missing(*_args, &_block) ⇒ Object



14
15
16
# File 'lib/cygnet/null_object.rb', line 14

def method_missing(*_args, &_block)
  self
end

Instance Method Details

#!Object



30
31
32
# File 'lib/cygnet/null_object.rb', line 30

def !
  true
end

#blank?Boolean

Returns:

  • (Boolean)


26
27
28
# File 'lib/cygnet/null_object.rb', line 26

def blank?
  nil?
end

#nil?Boolean

Returns:

  • (Boolean)


22
23
24
# File 'lib/cygnet/null_object.rb', line 22

def nil?
  true
end

#respond_to_missing?(_method_name, _include_private = true) ⇒ Boolean

Returns:

  • (Boolean)


18
19
20
# File 'lib/cygnet/null_object.rb', line 18

def respond_to_missing?(_method_name, _include_private = true)
  true
end

#to_aObject



46
47
48
# File 'lib/cygnet/null_object.rb', line 46

def to_a
  []
end

#to_aryObject



50
51
52
# File 'lib/cygnet/null_object.rb', line 50

def to_ary
  []
end

#to_cObject



62
63
64
# File 'lib/cygnet/null_object.rb', line 62

def to_c
  Complex(0)
end

#to_fObject



42
43
44
# File 'lib/cygnet/null_object.rb', line 42

def to_f
  0.0
end

#to_hObject



54
55
56
# File 'lib/cygnet/null_object.rb', line 54

def to_h
  {}
end

#to_hashObject



58
59
60
# File 'lib/cygnet/null_object.rb', line 58

def to_hash
  {}
end

#to_iObject



38
39
40
# File 'lib/cygnet/null_object.rb', line 38

def to_i
  0
end

#to_rObject



66
67
68
# File 'lib/cygnet/null_object.rb', line 66

def to_r
  Rational(0)
end

#to_sObject



34
35
36
# File 'lib/cygnet/null_object.rb', line 34

def to_s
  ''
end