Ruby で tap + break を使って条件によってメソッドチェーンを追加する

2024/04/15に公開

例えば次のように条件分岐によってクエリを追加する、しないを制御したい事があると思います。

def public_users(within_active: false)
  if within_active
    User.where(published: true).where.not(activated_at: nil)
  else
    User.where(published: true)
  end
end

これでもいいんですが #tap + break を使うとワンライナーでいい感じに書くこともできます。

def public_users(within_active: false)
  User.where(published: true)
      .tap { break _1.where.not(activated_at: nil) if within_active }
end

#tap 内で break するとその戻り値が #tap の戻り値になります。
逆に break しない場合はレシーバの値がそのまま返ってきます。
個人的には好きなんですがもうちょいスッキリ書きたいすねえ…。

GitHubで編集を提案

Discussion