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.

If any method call in the chain returns a falsy value, the chain aborts.

Examples:

Basic method chain

require 'mug/fragile-method-chain'
a._?.b.c.d._!

With the [] method

require 'mug/fragile-method-chain'
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



19
20
21
22
# File 'lib/mug/fragile-method-chain.rb', line 19

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



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

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.

Returns:

  • (Object)

    the final result of the chain, or the first falsy value



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

def _!
  @o
end

#_?Boolean

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

Returns:

  • (Boolean)


55
56
57
58
59
60
61
# File 'lib/mug/fragile-method-chain.rb', line 55

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)


64
65
66
67
# File 'lib/mug/fragile-method-chain.rb', line 64

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.

Returns:

  • (Boolean)


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

def respond_to_missing? meth, priv
  if __defer?
    @o.respond_to_missing? meth, priv
  else
    true
  end
end