Skip to content

Repository files navigation

Build StatusGem Version

Active Queryable

Active Queryable is a lightweight Ruby gem designed to simplify sorting, filtering, and paginating models in Rails applications. Its intuitive API and seamless integration with ActiveModel make building complex queries a breeze.

Features

  • Easy integration with Rails models.
  • Support for dynamic sorting, filtering, and pagination.
  • Compatible with JSON:API specification for pagination parameters.
  • Extensible through custom scopes for advanced filtering needs.

Installation

Ensure you have Rails >= 5.2 (or specify another version if needed) and then add Active Queryable to your Gemfile:

gem'active_queryable'

or alternatively bundle add active_queryable

Usage

First, include the as_queryable method in your model to enable the gem.

classPerson < ActiveModel::Base# Add this line to enable the gemas_queryableend

Then, configure the order and filters you want to use:

classPerson < ActiveModel::Base# Add this line to enable the gemas_queryable# Configure order and filtersqueryableorder: {name: :asc},filter: [:name]end

This will allow you to query your model using the query_by method:

Person.query_by(order: '-name')# SELECT * FROM people ORDER BY name DESC LIMIT 25Person.query_by(filter: {name: 'john'})# SELECT * FROM people WHERE people.name = 'john' LIMIT 25

Pagination

You can also use pagination, using kaminari under the hood:

Person.query_by(per: 20,page: 2)# SELECT * FROM people LIMIT 20 OFFSET 20# Accepts also JSON:API-styled parametersPerson.query_by(page: {number: 2,size: 20})# SELECT * FROM people LIMIT 20 OFFSET 20

Custom scopes and orders

You can also use custom scopes to extend the filtering and ordering capabilities.

The gem will look for a scope with the same name as the filter, and a method with the same name as the order.

classPerson < ActiveModel::Base# Add this line to enable the gemas_queryable# Configure order and filtersqueryableorder: {fullname: :asc},filter: [:name_like]# the `of_name_like` scope will be used when filtering by `name_like`scope:of_name_like,->(name){where('name LIKE ?',"%#{name}%")}# the `by_name` method will be used when ordering by `name`order:by_name,->(direction){order(firstname: direction,lastname: direction)}end

About Monade

monade

active_queryable is maintained by mònade srl.

We <3 open source software. Contact us for your next project!

About

A light and simple gem for sorting / filtering / paginating a model in Rails.

Topics

Resources

Stars

4 stars

Watchers

6 watching

Forks

Releases

Packages

Used by

Contributors

Languages