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) ⇒ 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
	@o = o
	@chain = []
end

Dynamic Method Handling

This class handles dynamic methods through the method_missing method

#method_missing(*a, &b) ⇒ Object

Record the method args/block



34
35
36
37
# File 'lib/mug/fragile-method-chain.rb', line 34

def method_missing *a, &b #:nodoc:
	@chain << [a,b]
	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
28
29
30
31
# File 'lib/mug/fragile-method-chain.rb', line 25

def _!
	@chain.inject(@o) do |o,x|
		a,b = x
		break o unless o
		o.__send__(*a, &b)
	end
end

#_?Boolean

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

Returns:

  • (Boolean)


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

def _? #:nodoc:
	@chain << [[ :_? ],nil]
	self
end