/qry_filter

A Rails add-on for handling ActiveRecord::Relation filters

Primary LanguageRubyMIT LicenseMIT

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.