Criteria pattern applied for organizing complex filtering

When a complex filtering solution is required to be built the code becomes a mess more often than not. Filtering records is a pretty simple task on it’s own: just apply required ActiveRecord scopes on a certain conditions of the given params. Those conditions, however, can become much more complex than you expect. As a result, the code spreads out in controller, models and logic layers making it hardly readable and maintainable. Further down, I’ll describe a simple approach that’ll help avoid such annoyances.

First off, we want to delegate all the filtering, ordering, pagination and other collection presentation stuff to a separate class so that controller code became as simple as possible (example code uses CanCan gem, which is augmenting collection pattern usage):

I assume that this is not a single occurrence of collection functionality in the system. So, common behavior can be extracted to some base class:

Here comes Criteria Pattern in play. The idea is to encapsulate collection aspects into small manageable pieces of code and chain them by means of extending collection object with those modules:

Certainly, my example above is oversimplified and does not differ from the base class. Let’s add some functionality to make this example have a bit more sense:

For the sake of making the code reusable (e. g. for reports, exports etc.) some modules can be applied by calling separate method. You can see it in the first code insert for controller: methods #paginated and #eager_loaded. Let’s add them to our collection:

Sure thing, you have to be accurate with chaining #items methods. Some things will not work together, e.g. using include for eager loading in one module and defining custom select fields in another and then chaining them together.

So, this is it. I hope this collection approach will come in handy in your work.