Skip to content

Commit

Permalink
where support multiple keys
Browse files Browse the repository at this point in the history
  • Loading branch information
kbrock committed Feb 3, 2016
1 parent 3846eaa commit 575fe9d
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 13 deletions.
30 changes: 17 additions & 13 deletions lib/active_hash/base.rb
Expand Up @@ -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?
Expand Down
12 changes: 12 additions & 0 deletions spec/active_hash/base_spec.rb
Expand Up @@ -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
Expand Down Expand Up @@ -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
Expand Down

0 comments on commit 575fe9d

Please sign in to comment.