From 575fe9d9b5afdd44eaadac661c34043e6b9cb807 Mon Sep 17 00:00:00 2001 From: Keenan Brock Date: Wed, 3 Feb 2016 10:04:08 -0500 Subject: [PATCH] where support multiple keys --- lib/active_hash/base.rb | 30 +++++++++++++++++------------- spec/active_hash/base_spec.rb | 12 ++++++++++++ 2 files changed, 29 insertions(+), 13 deletions(-) diff --git a/lib/active_hash/base.rb b/lib/active_hash/base.rb index 356b2089..08d9acb2 100644 --- a/lib/active_hash/base.rb +++ b/lib/active_hash/base.rb @@ -155,27 +155,31 @@ def all(options={}) end def where(options) - return @records if options.nil? - (@records || []).select do |record| - match_options?(record, options) - end - end + return @records if options.blank? - def find_by(options) - return all.first if options.nil? - options.symbolize_keys! - - if id = options.delete(:id) - candidates = Array(id).map { |i| find_by_id(id) } + # use index if searching by id + if (ids = (options.delete(:id) || options.delete("id"))) + candidates = Array.wrap(ids).map { |id| find_by_id(id) } end + return candidates if options.blank? - (candidates || all).detect do |record| + (candidates || @records || []).select do |record| match_options?(record, options) end end + def find_by(options) + where(options).first + end + def match_options?(record, options) - options.all? { |col, match| record[col] == match } + options.all? do |col, match| + if match.kind_of?(Array) + match.include?(record[col]) + else + record[col] == match + end + end end private :match_options? diff --git a/spec/active_hash/base_spec.rb b/spec/active_hash/base_spec.rb index b5c2c0c4..55a0b3e3 100644 --- a/spec/active_hash/base_spec.rb +++ b/spec/active_hash/base_spec.rb @@ -226,6 +226,10 @@ class Region < ActiveHash::Base Country.where(nil).should == Country.all end + it "returns all records when an empty hash" do + Country.where({}).should == Country.all + end + it "returns all data as inflated objects" do Country.where(:language => 'English').all? { |country| country.should be_kind_of(Country) } end @@ -264,6 +268,14 @@ class Region < ActiveHash::Base ] end.should raise_error(ActiveHash::IdError) end + + it "returns multiple records for multiple ids" do + expect(Country.where(:id => %w(1 2)).map(&:id)).to match_array([1,2]) + end + + it "filters records for multiple values" do + expect(Country.where(:name => %w(US Canada)).map(&:name)).to match_array(%w(US Canada)) + end end describe ".find_by" do