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
endIn Controller
# app/controllers/users_controller.rb
class UsersController < ApplicationController
def index
users = filter User, params
# ...
end
endOther 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_byandfilter_class -
filter_bymaps with your filter class methods e.g.[:id]will only triggerby_idmethod. If empty, all filters will be triggered. -
filter_classallows you to set a specific class when needed.
Installation
Add this line to your application's Gemfile:
gem 'qry_filter'And then execute:
$ bundleOr install it yourself as:
$ gem install qry_filterGenerate app/filters/application_filter.rb:
$ rails g qry_filter:installInclude QryFilter in ApplicationController
class ApplicationController < ActionController::Base
include QryFilter
endContributing
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.