Project

qry_filter

0.0
No release in over 3 years
Low commit activity in last 3 years
A Rails add-on for handling query filters
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
 Dependencies

Development

~> 13.0.1
~> 3.8
~> 0.79.0
~> 1.4.1
 Project Readme

Gem Version Maintainability Test Coverage

QryFilter

QryFilter aka "QueryFilter" is a simple Rails gem that provides a pattern and helper when dealing with lots of filter clauses in your ActiveRecord query.

Usage

Filter Class

# app/filters/user_filter.rb
class UserFilter < ApplicationFilter
  def by_id
    @scope = @scope.where(id: @filter_hash[:id])
  end

  def by_age
    @scope = @scope.where(age: @filter_hash[:age])
  end
end

In Controller

# app/controllers/users_controller.rb
class UsersController < ApplicationController
  def index
    users = filter User, params
    # ...
  end
end

Other options

Class Method:

params = {id: [1, 2, 3], age: [18, 20]}
users = User.where(happy: true)

QryFilter.compose(users, params, filter_by: [:id, :age], filter_class: UserFilter)

Helper:

filter User, params, filter_by: [:id, :age], filter_class: UserFilter
  • The first argument accepts ActiveRecord::Relation or model class name.
  • The second is for key-value pair of data you want to pass to your filter class.
  • The last argument is an optional hash and allows you to set filter_by and filter_class
  • filter_by maps with your filter class methods e.g. [:id] will only trigger by_id method. If empty, all filters will be triggered.
  • filter_class allows you to set a specific class when needed.

Installation

Add this line to your application's Gemfile:

gem 'qry_filter'

And then execute:

$ bundle

Or install it yourself as:

$ gem install qry_filter

Generate app/filters/application_filter.rb:

$ rails g qry_filter:install

Include QryFilter in ApplicationController

class ApplicationController < ActionController::Base
  include QryFilter
end

Contributing

Fork the repo and submit a pull request. Please follow this Rails style guide.

License

The gem is available as open source under the terms of the MIT License.