active-hash / active_hash

A readonly ActiveRecord-esque base class that lets you use a hash, a Yaml file or a custom file as the datasource
MIT License
1.19k stars 178 forks source link

find_by with nil value will return an object with an empty string #293

Closed tomohung closed 8 months ago

tomohung commented 9 months ago

Environment

Problem

Running the script from the console

class Vehicle < ActiveHash::Base
  self.data = [
    {
      id: 1,
      name: "Wagon",
      code: "1"
    },
    {
      id: 2,
      name: "rocket",
      code: ""
    }
  ]
end

Vehicle.find_by(code: "")&.id
# expected: 2, return: 2

Vehicle.find_by(code: nil)&.id
# expected: nil, return: 2

as the second example should return nil but not the record (id: 2)

Potential solution

It looks like we introduced from https://github.com/active-hash/active_hash/pull/268/files#diff-3d428d32c562c13eaacc6f541b1c94625f24cf74f1c42a9f7ee06999647773dbR42 that didn't consider nil case.

This could solve the issue

module ActiveHash
  class Relation
    class Condition
      def normalize(value)
        return value if value.nil?

        value.respond_to?(:to_s) ? value.to_s : value
      end
    end
  end
end