In my project, a large number of POROs are composed from various data sources such as external APIs. The objects looks like:
{id: 1, name: 'Peter', age: 8}, {id: 2, name: 'Jack', age: 4}, {id: 3, name: 'Tom', age: 12}
I would like to have an ActiveRecord-like interface to query these objects. Such as Person.where(name: 'Jack')
and Person.where("age > ?", 5)
My attempt looks like this:
class Query
def initialize(objs)
@objs = objs
end
def where(name: nil, age: nil)
result = @objs
result = result.select{|x| x.name == name} if name
result = result.select{|x| x.age == age} if age
result
end
end
It works, but I don't think it is a nice solution:
- What if there are 20 attributes? The
where
method can become very long and error-prone. - What about other useful ActiveRecord query? e.g.
find
,find_by
,pluck
,order by
and many others. Even if I can implement them all, how do I "chain" multiple queries? - Efficiency: How to optimize the queries like the sql query planner?
- Most importantly, how do I implement
Person.where("age > ?", 5)
and other flexible queries?
Am I missing anything? I feel like I am re-inventing the wheel.
I've checked ActiveModel but unfortunately it doesn't have a query system.
Are there any gems out there that can help?