SimpleFilter
Simple filter for replacing the awkward search method or scopes of models.
Installation
Add this line to your application's Gemfile:
gem 'simple_filter'
And then execute:
$ bundle
Or install it yourself as:
$ gem install simple_filter
Usage
SimpleFilter was designed to replace the awkward search method or scopes in your models when
doing filtering. It encapsulate all of the filter logic to filter class, which will make your
model more cleaner. And it defaults to provider sort and pagination filter, relieving you from
keep writing sort or pagination filter for each models.
To start using SimpleFilter you just need to generate a filter class for your model:
rails generate simple_filter your_model_name
Then in your app/filters/ directory you'll find filter file like this:
class UserFilter < SimpleFilter::Base
# Rewrite default filter options in case you need.
# config per_page: 20, order_by: :name
# There're default filters including :sort, :pagination. You can use them along with
# your custom filters like this:
#
filter :sort
#
# private
#
# def by_name
# if params[:name].present?
# @scope = scope.where(:name => params[:name])
# end
# end
end
Here you can customize your filters with the filter DSL. For example:
class UserFilter < SimpleFilter::Base
filter :by_name, :sort, :pagination
private
def by_name
if params[:name].present?
@scope = scope.where(:name => params[:name])
end
end
end
In case your filter class name was not consist with the ActiveModel name, you could
use scope DSL to config this manually:
class PersonFilter < SimpleFilter::Base
scope :user
filter :sort
# other filters
end
In your controller you can use it like this:
class Admin::UsersController < Admin::BaseController
def index
@users = UserFilter.all(params)
end
# other actions...
end
As you see it, it's very simple, enjoy it!
Contributing
- Fork it
- Create your feature branch (
git checkout -b my-new-feature) - Commit your changes (
git commit -am 'Added some feature') - Push to the branch (
git push origin my-new-feature) - Create new Pull Request