Conditionally chaining where blocks

Does anyone have any ideas for solving the following problem?

Looking to write a method that takes in a hash that has optional keys and based on whether there are certain keys present they conditionally chain where clauses.

{
  name: "John",
  age: 23
}

Would trigger something like persons.where(age: 23).where { name.ilike("%John%") }

But if I passed something like:

{ age: 23 }

Would trigger something like persons.where(age: 23)

Thanks!

You could do this:

conditions = { age: 21, name: "John" }

matching_users = conditions.reduce(users) do |r, (k, v)|
  case v
  when String
    r.where(r[k].ilike("%#{v}%"))
  else
    r.where(k => v)
  end
end

Hope this helps.

2 Likes