From e5661d87bf1bb2ac30aaa98ccc2ae4c5dd47d993 Mon Sep 17 00:00:00 2001 From: Keenan Brock Date: Wed, 29 Nov 2023 16:56:34 -0500 Subject: [PATCH] Treat nil and blank values as different Before: When searching for "", it found records with a nil value. After: It will find nil values when searching for nil It will not find nil values when searching for '' --- lib/active_hash/condition.rb | 2 +- spec/active_hash/base_spec.rb | 11 ++++++++++- 2 files changed, 11 insertions(+), 2 deletions(-) diff --git a/lib/active_hash/condition.rb b/lib/active_hash/condition.rb index cf78b052..26dce78d 100644 --- a/lib/active_hash/condition.rb +++ b/lib/active_hash/condition.rb @@ -39,6 +39,6 @@ def matches_value?(value, comparison) end def normalize(value) - value.respond_to?(:to_s) ? value.to_s : value + value.respond_to?(:to_s) ? value&.to_s : value end end diff --git a/spec/active_hash/base_spec.rb b/spec/active_hash/base_spec.rb index f105dca4..8a9a4262 100644 --- a/spec/active_hash/base_spec.rb +++ b/spec/active_hash/base_spec.rb @@ -465,7 +465,8 @@ class Region < ActiveHash::Base Country.data = [ {:id => 1, :name => "US", :language => 'English'}, {:id => 2, :name => "Canada", :language => 'English'}, - {:id => 3, :name => "Mexico", :language => 'Spanish'} + {:id => 3, :name => "Mexico", :language => 'Spanish'}, + {:id => 5, :name => "Any", :language => nil} ] end @@ -524,6 +525,14 @@ class Region < ActiveHash::Base it "returns nil when passed a wrong id" do expect(Country.find_by(:id => 4)).to be_nil end + + it "finds record by nil value" do + expect(Country.find_by(:language => nil).id).to eq(5) + end + + it "doesn't finds nil records when searching for ''" do + expect(Country.find_by(:language => '')).to be_nil + end end describe ".find_by!" do