From 2c36e6a50041f2f524f22f3eff3097b365ddc330 Mon Sep 17 00:00:00 2001 From: Yuji Yaginuma Date: Tue, 27 Aug 2024 14:46:41 +0900 Subject: [PATCH] Fix the behavior when passing nil to `exists?` Currently, the behavior when passing `nil` to `exists?` doesn't match with Rails's behavior. Rails always returns `false`, but ActiveHash not. https://github.com/rails/rails/blob/5a0b2fa5a3be6ffd49fa7f1c3544c1da403c9cb5/activerecord/lib/active_record/relation/finder_methods.rb#L367 This PR changes the behavior to match with Rails's. --- lib/active_hash/base.rb | 6 +++--- spec/active_hash/base_spec.rb | 6 ++++++ 2 files changed, 9 insertions(+), 3 deletions(-) diff --git a/lib/active_hash/base.rb b/lib/active_hash/base.rb index 0898047..144a0c3 100644 --- a/lib/active_hash/base.rb +++ b/lib/active_hash/base.rb @@ -102,12 +102,12 @@ def data=(array_of_hashes) end end - def exists?(args = nil) + def exists?(args = :none) if args.respond_to?(:id) record_index[args.id.to_s].present? - elsif args == false + elsif !args false - elsif args.nil? + elsif args == :none all.present? elsif args.is_a?(Hash) all.where(args).present? diff --git a/spec/active_hash/base_spec.rb b/spec/active_hash/base_spec.rb index d0af652..9d175e4 100644 --- a/spec/active_hash/base_spec.rb +++ b/spec/active_hash/base_spec.rb @@ -1169,6 +1169,12 @@ def continent end end + context "when nil is passed" do + it "return nil" do + expect(Country.exists?(nil)).to be_falsy + end + end + describe "with matches" do context 'for a record argument' do it "return true" do