Class: FragileMethodChain
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
-
#_! ⇒ Object
Finalises the FragileMethodChain.
-
#_? ⇒ Boolean
Explicitly invoke :_? as a method in the chain.
-
#__defer? ⇒ Boolean
Return true iff @o is deferable.
-
#initialize(o, falsy: true) ⇒ FragileMethodChain
constructor
Creates a FragileMethodChain which will send its first method to
o
. -
#method_missing(*a, &b) ⇒ Object
Delegate the method args/block.
-
#respond_to_missing?(meth, priv) ⇒ Boolean
If the object is resolved, defer.
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.
48 49 50 51 52 53 54 |
# File 'lib/mug/fragile-method-chain.rb', line 48 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.
57 58 59 60 |
# File 'lib/mug/fragile-method-chain.rb', line 57 def __defer? return @o if @falsy ! @o.nil? end |
#respond_to_missing?(meth, priv) ⇒ Boolean
If the object is resolved, defer. Otherwise, sure, I respond to anything, I guess.
39 40 41 42 43 44 45 |
# File 'lib/mug/fragile-method-chain.rb', line 39 def respond_to_missing? meth, priv if __defer? @o.respond_to_missing? meth, priv else true end end |