ActiveRecord like where for array of hashes in ruby
Edit : Updated the code as per the suggestions made by Masklinn.
Recently I was working on Issue#1 of my Soulmate Rails gem, which is a very simple and obvious optimization that I should have thought of myself. Thanks to lephyrius though for pointing it out. In my search method I was looping through the search results and calling find on each to get it from db. The fix involved to instead use a single where for all ids so that it translates to a single db call. A simple fix as well as an optimization.
However once I implemented it, I notice my tests were failing. On closer
inspection I found they are failing because the models I created for testing
using supermodel gem, didn’t have
a where
method. For a moment I thought WTF, and then I headed on to
supermodel git repo and looked through the source and to my surprise, it in
fact did not implement a where
method. So I took it upon myself to do it.
Here’s the generic code I wrote that could be applied to any array of hashes :
def where(records, options)
records.select do |r|
options.all? do |k, v|
if v.is_a?(Enumerable)
v.include?(r[k])
else
r[k] == v
end
end
end
end
Now you can do
# Eg.1)
where(records, :first_name => 'Dhruva', :last_name => 'Sagar')
# Eg.2)
where(records, :id => [1, 2, 3])
And you will get what you’d expect.
I updated supermodel in my fork
to support such a where
method and have sent the original author a pull
request, hopefully it will get
pulled soon.
All my tests pass now! Yay! I have released v0.3.0 of Soulname Rails. Be sure to check it out.
PS : How about a code review ? Is this optimal or can it be improved further ? I’d like to hear thoughts from others.