Sometimes we want to use chain method and Ruby also provides it.
It seems wonderful, BUT (Always BUT appears when everything is good 😭) the some chain methods only can run under some conditions. But we cannot do as like
obj.new
.add(xxx) if xxx.present? # Here will happen an error.
.create
.save
We need to do something for fixing kinda problem.
Actually, Ruby provides a excellent method is tap
, but tap
is inconvenient to use. The return
object will be object self so we're not able to chain them together.
In order to chain together, we use the block
or yield
to achieve it. The solution is here!
class Object
#
# obj.tap { |o| ... } will be return origin +object+.
# This is a method for checking whether chain methods is continuous or not. For example,
#
# A.new.tap { |o| o.create(...) if id }.save
#
# The function is totally the same as +Object::tap+, but this is optimize the return object,
# let you use them smoothly.
#
# Also see Object::tap
#
# @return [<object>] +nil+ or an +object+
#
def tap_chain
res = yield self if block_given?
res || self
end
end