Class: NullObject

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

Constant Summary collapse

VERSION =
"0.0.1"

Instance Method Summary collapse

Constructor Details

#initialize(*methods, &return_block) ⇒ NullObject

Returns a new instance of NullObject.



4
5
6
7
8
9
10
11
12
# File 'lib/null_object.rb', line 4

def initialize(*methods, &return_block)
  if methods.first.is_a?(Hash)
    @methods = methods.first
  else
    @methods = methods
  end

  @return_block = return_block
end

Dynamic Method Handling

This class handles dynamic methods through the method_missing method

#method_missing(method, *args) ⇒ Object



14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
# File 'lib/null_object.rb', line 14

def method_missing(method, *args)
  matched = false
  return_value = if @methods.empty?
                   matched = true and __global_return_value__
                 elsif @methods.is_a?(Hash) && @methods.key?(method.to_sym)
                   matched = true and @methods[method.to_sym]
                 elsif @methods.is_a?(Enumerable) && @methods.include?(method.to_sym)
                   matched = true and __global_return_value__
                 end

  if matched
    # Next time, there'll be a real method and we'll avoid the method_missing
    # chain
    singleton_class = class << self; self; end;
    singleton_class.__send__(:define_method, method) { return_value }

    return_value
  else
    super
  end
end