Class: MaybeChain::MaybeWrapper

Inherits:
Delegator
  • Object
show all
Defined in:
lib/maybe-chain.rb

Instance Method Summary collapse

Constructor Details

#initialize(obj, rescuables = []) ⇒ MaybeWrapper

Returns a new instance of MaybeWrapper.

Raises:

  • (ArgumentError)


7
8
9
10
11
12
13
14
15
16
17
# File 'lib/maybe-chain.rb', line 7

def initialize(obj, rescuables = [])
  raise ArgumentError unless (rescuables.is_a?(Class) && rescuables <= Exception) || rescuables.is_a?(Array)

  if rescuables.is_a?(Exception)
    @rescuables = [rescuables]
  else
    @rescuables = rescuables
  end

  @obj = obj.nil? ? Nothing.instance : obj
end

Dynamic Method Handling

This class handles dynamic methods through the method_missing method

#method_missing(m, *args, &block) ⇒ Object



31
32
33
34
35
36
37
38
39
# File 'lib/maybe-chain.rb', line 31

def method_missing(m, *args, &block)
  if nothing?
    self.__getobj__.__send__(m, @rescuables, &block)
  else
    MaybeWrapper.new(super, @rescuables)
  end
rescue *@rescuables
  build_nothing
end

Instance Method Details

#__getobj__Object



19
20
21
# File 'lib/maybe-chain.rb', line 19

def __getobj__
  @obj
end

#inspectObject



23
24
25
# File 'lib/maybe-chain.rb', line 23

def inspect
  "<Maybe: #{@obj.inspect}>"
end

#just?Boolean

Returns:

  • (Boolean)


45
46
47
# File 'lib/maybe-chain.rb', line 45

def just?
  !nothing?
end

#lift(method_name, *args, &block) ⇒ Object



53
54
55
56
57
58
59
60
61
# File 'lib/maybe-chain.rb', line 53

def lift(method_name, *args, &block)
  return build_nothing if nothing?
  return build_nothing if args.any?(&:nothing?)

  extracts = args.map {|arg| arg.is_a?(MaybeChain::MaybeWrapper) ? arg.value : arg}
  MaybeWrapper.new(value.__send__(method_name, *extracts, &block), @rescuables)
rescue *@rescuables
  build_nothing
end

#nothing?Boolean

Returns:

  • (Boolean)


41
42
43
# File 'lib/maybe-chain.rb', line 41

def nothing?
  @obj.is_a? Nothing
end

#to_sObject



27
28
29
# File 'lib/maybe-chain.rb', line 27

def to_s
  @obj.to_s
end

#valueObject



49
50
51
# File 'lib/maybe-chain.rb', line 49

def value
  nothing? ? nil : @obj
end