Module: Tins::Null

Included in:
NullClass, NullPlus
Defined in:
lib/tins/null.rb

Overview

Tins::Null provides an implementation of the null object pattern in Ruby.

The null object pattern is a behavioral design pattern that allows you to avoid null references by providing a default object that implements the expected interface but does nothing. This eliminates the need for null checks throughout your codebase.

This module provides the core functionality for null objects, including:

  • Method missing behavior that returns self

  • Type conversion methods that return appropriate default values

  • Debugging support through NullPlus

Examples:

Basic usage

# Instead of checking for nil:
user = find_user(id)
if user
  user.name
else
  "Unknown"
end

# You can use the null object:
user = find_user(id) || Tins::NULL
user.name  # => "" (instead of nil)

With NullPlus for debugging

user = find_user(id) || Tins::NullPlus.new(value: "Unknown", caller: caller)
user.value  # => "Unknown"

Defined Under Namespace

Modules: Kernel

Instance Method Summary collapse

Dynamic Method Handling

This class handles dynamic methods through the method_missing method

#method_missingself

Handle missing methods by returning self, allowing method chaining.

Returns:

  • (self)

    Always returns self to allow chaining



34
35
36
# File 'lib/tins/null.rb', line 34

def method_missing(*)
  self
end

Instance Method Details

#as_jsonnil

Convert to JSON (for compatibility with JSON serialization).

Returns:

  • (nil)

    returns nil value



97
98
99
# File 'lib/tins/null.rb', line 97

def as_json(*)
  nil
end

#blank?Boolean

Check if object is blank.

Returns:

  • (Boolean)

    Always returns true



90
91
92
# File 'lib/tins/null.rb', line 90

def blank?
  true
end

#const_missingself

Handle missing constants by returning self.

Returns:

  • (self)

    Always returns self



41
42
43
# File 'lib/tins/null.rb', line 41

def const_missing(*)
  self
end

#inspectString

Inspect representation.

Returns:



76
77
78
# File 'lib/tins/null.rb', line 76

def inspect
  'NULL'
end

#nil?Boolean

Check if object is nil.

Returns:

  • (Boolean)

    Always returns true



83
84
85
# File 'lib/tins/null.rb', line 83

def nil?
  true
end

#to_aArray

Convert to array.

Returns:

  • (Array)

    Empty array



69
70
71
# File 'lib/tins/null.rb', line 69

def to_a
  []
end

#to_fFloat

Convert to float.

Returns:

  • (Float)

    Zero as float



55
56
57
# File 'lib/tins/null.rb', line 55

def to_f
  0.0
end

#to_iInteger

Convert to integer.

Returns:

  • (Integer)

    Zero



62
63
64
# File 'lib/tins/null.rb', line 62

def to_i
  0
end

#to_jsonString

Convert to JSON string.

Returns:



104
105
106
# File 'lib/tins/null.rb', line 104

def to_json(*)
  'null'
end

#to_sString

Convert to string representation.

Returns:



48
49
50
# File 'lib/tins/null.rb', line 48

def to_s
  ''
end