Class: FragileMethodChain

Inherits:
Object show all
Defined in:
lib/mug/fragile-method-chain.rb

Overview

Invokes a method chain until one method returns a falsy value.

For example:

a._?.b.c.d._!
nested_hash._?[:a][:b][:c]._!

Instance Method Summary collapse

Constructor Details

#initialize(o, falsy: true) ⇒ FragileMethodChain

Creates a FragileMethodChain which will send its first method to o



14
15
16
17
# File 'lib/mug/fragile-method-chain.rb', line 14

def initialize o, falsy: true
	@o = o
	@falsy = falsy
end

Dynamic Method Handling

This class handles dynamic methods through the method_missing method

#method_missing(*a, &b) ⇒ Object

Delegate the method args/block



30
31
32
33
34
35
# File 'lib/mug/fragile-method-chain.rb', line 30

def method_missing *a, &b #:nodoc:
	if __defer?
		@o = @o.__send__(*a, &b)
	end
	self
end

Instance Method Details

#_!Object

Finalises the FragileMethodChain.

The final result will be the first nil or false value returned in the chain, or its end result.



25
26
27
# File 'lib/mug/fragile-method-chain.rb', line 25

def _!
	@o
end

#_?Boolean

Explicitly invoke :_? as a method in the chain.

Returns:

  • (Boolean)


38
39
40
41
42
43
44
# File 'lib/mug/fragile-method-chain.rb', line 38

def _? #:nodoc:
	# Unconditionally invoke it, so the eventual _! doesn't fail
	#if __defer?
		@o = @o.__send__(:_?)
	#end
	self
end

#__defer?Boolean

Return true iff @o is deferable.

Returns:

  • (Boolean)


47
48
49
50
# File 'lib/mug/fragile-method-chain.rb', line 47

def __defer?
	return @o if @falsy
	! @o.nil?
end