Skip to content

Instantly share code, notes, and snippets.

@pokk
Created July 28, 2017 02:48
Show Gist options
  • Save pokk/a5766e6caf86c938adeacec451e080bf to your computer and use it in GitHub Desktop.
Save pokk/a5766e6caf86c938adeacec451e080bf to your computer and use it in GitHub Desktop.
Tap a chain methods with condition statement.

Introcution

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.

Solution

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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment