Filterable Gem

Here is a useful Ruby gem from Toschas!

Filterable gem provides an easy way to filter content, and it can be integrated in any application that uses Active Record.

Filtering displayed content is a part of almost any web app.

In Rails (or any other ActiveRecord applications) it’s usually done with scopes:

class Post < ActiveRecord::Base
scope :by_published, ->(value) { where(published: value) }
scope :by_author_id, ->(author_id) { where(author_id: author_id) }
end

which then allows you to do something like the following:

Post.by_published(true)
Post.by_author_id(1)
Post.by_published(true).by_author_id(1)

The number of scopes tend to grow big in an average-sized Rails app and it becomes pretty tiring and repetitive work to maintain them. The model’s fields which are allowed to be filtered by must also be configured manually.

Our solution: Filterable gem.

Filterable gem automates the process of defining and using filters on your models by providing a simple API. It returns an ActiveRecord Collection so it can be chained to other methods (same as using scopes).

class Post < ActiveRecord::Base
filter_by: :published, :author_id
end

and then in the controller, you can simply do the following:

def index
Post.filter(allowed_filters)
end
# allowed filters being defined like this
protected
def allowed_filters
params.permit(:by_published, :by_author_id)
end

Filterable also supports filtering by related model’s fields, comparing numeric values and dates and defining custom filters for any special case you may have.

You can check it out in more detail here.