Git Product home page Git Product logo

filterer's Introduction

⚠️ Warning: This project is no longer maintained.

📝 This project is not compatible with ruby 2.6.6 or rails 6 and it is no longer maintained.

Filterer status coverage codeclimate gem

Filterer lets your users easily filter results from your ActiveRecord models. What does that mean? Let's imagine a page in your application that lists the results of Person.all:

Name              Email           Admin?
----              ----            ----
Adam Becker       [email protected]     true
Barack Obama      [email protected]       false
Joe Biden         [email protected]   true

What if you want to let your users filter the results by name? Or email? Or whether or not the Person is an admin? Where does that logic go?

One answer could be your controller. You could progressively build up a query, like so:

@results = Person.all
@results = @results.where(name: params[:name]) if params[:name].present?
@results = @results.where(email: params[:email]) if params[:email].present?
@results = @results.where(admin: true) if params[:admin].present?

But you can see how that could get ugly fast. Especially when you add in sorting and pagination.

Another answer could be in your models. But passing a bunch of query parameters to a model isn't really a good practice either.

Enter Filterer.

Using Filterer

First, add gem 'filterer' to your Gemfile.

Next, you create a Filterer that looks like this:

# app/filterers/person_filterer.rb

class PersonFilterer < Filterer::Base
  def param_name(x)
    results.where(name: x)
  end

  def param_email(x)
    results.where('LOWER(email) = ?', x)
  end

  def param_admin(x)
    results.where(admin: true)
  end

  # Optional default params
  def defaults
    {
      direction: 'desc'
    }
  end

  # Optional default filters
  def apply_default_filters
    results.where('deleted_at IS NULL')
  end
end

And in your controller:

class PeopleController < ApplicationController
  def index
    @people = Person.filter(params)
  end
end

Now, when a user visits /people, they'll see Adam, Barack, and Joe, all three people. But when they visit /people?name=Adam%20Becker, they'll see only Adam. Or when they visit /people?admin=t, they'll see only Adam and Joe.

Specifying the Filterer class to use

Filterer includes a lightweight ActiveRecord adapter that allows us to call filter on any ActiveRecord::Relation like in the example above. By default, it will look for a class named [ModelName]Filterer. If you wish to override this, you have a couple of options:

You can pass a :filterer_class option to the call to filter:

Person.filter(params, filterer_class: 'AdvancedPersonFilterer')

Or you can bypass the ActiveRecord adapter altogether:

AdvancedPersonFilterer.filter(params, starting_query: Person.all)

Pagination

Filterer relies on either Kaminari or will_paginate for pagination. You must install one of them if you want to paginate your records.

If you have either of the above gems installed, Filterer will automatically paginate your records, fetching the correct page for the ?page=X URL parameter. By default, filterer will display 20 records per page.

Overriding per_page

class PersonFilterer < Filterer::Base
  self.per_page = 30 # defaults to 20
end

Allowing the user to override per_page

class PersonFilterer < Filterer::Base
  self.per_page = 20
  self.allow_per_page_override = true
end

Now you can append ?per_page=50 to the URL.

Note: To prevent abuse, this value will still max-out at 1000 records per page.

Disabling pagination

class NoPaginationFilterer < PersonFilterer
  self.per_page = nil
end

or

Person.filter(params, skip_pagination: true)

Sorting the results

Filterer provides a slightly different DSL for sorting your results. Here's a quick overview of the different ways to use it:

class PersonFilterer < Filterer::Base
  # '?sort=name' will order by LOWER(people.name). If there is no sort parameter,
  # we'll default to this anyway.
  sort_option 'name', 'LOWER(people.name)', default: true

  # '?sort=id' will order by id. This is used as a tiebreaker, so if two records
  # have the same name, the one with the lowest id will come first.
  sort_option 'id', tiebreaker: true

  # '?sort=occupation' will order by occupation, with NULLS LAST.
  sort_option 'occupation', nulls_last: true

  # '?sort=data1', '?sort=data2', etc. will call the following proc, passing the
  # match data. It returns a string that gets passed to the ORDER BY clause.
  sort_option Regexp.new('data([0-9]+)'), -> (matches) {
    "(ratings -> '#{matches[1]}')"
  }
end

Since paginating records without an explicit ORDER BY clause is a no-no, Filterer orders by [table_name].id asc if no sort options are provided.

Disabling the ordering of results

For certain queries, you might want to bypass the ordering of results:

Person.filter(params, skip_ordering: true)

Passing arbitrary data to the Filterer

class OrganizationFilterer < Filterer::Base
  def starting_query
    if opts[:is_admin]
      Organization.all.with_deleted_records
    else
      Organization.all
    end
  end
end

OrganizationFilterer.filter(params, is_admin: current_user.admin?)

License

MIT

filterer's People

Contributors

ajb avatar beerlington avatar olliebennett avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

filterer's Issues

Usage of "chain" and "filter" in Ruby 2.6

Ruby 2.6.0 was released this week, and introduces Enumerator::Chain and Enumerable#filter.

The filterer gem already implements the chain and filter methods on an ActiveRecord collection.

On older rubies (<2.6) everything works fine;

# Ruby 2.5.x
> User.where('1=1').chain
=> [#<User:0x00007fe8bbf5f9c3 ... etc as expected.

However, on new rubies (>2.6.0) we see the following problem;

# Ruby 2.6.0
> User.where('1=1').chain
=> #<Enumerator::Chain: ...>

It seems the simplest solution is to rename or avoid the .chain and .filter methods in this gem.

Thoughts?

Rails 5 - to_hash is deprecated

DEPRECATION WARNING: Method to_hash is deprecated and will be removed in Rails 5.1, as `ActionController::Parameters` no longer inherits from hash. Using this deprecated behavior exposes potential security problems. If you continue to use this method you may be creating a security vulnerability in your app that can be exploited. Instead, consider using one of these documented methods which are not deprecated: http://api.rubyonrails.org/v5.0.0.1/classes/ActionController/Parameters.html

Baked in limit / offset?

I wanted to be able to filter what my API returns and I used filterer to do this. I was surprised to see that there was a limit of 10. I was able to find the code in filterer that does this and it does not seem like it can be overriden. Is my use case of the Filterer gem valid? Or should it not be used for an API?

Using filterer without pagination

I like the way filterer makes it easy to pass params and get the result without having a bunch of ifs. However, I don't always use it for an API -- sometimes I use it in some service object to allow fellow developers pass in options that are in turn used in the filterer object. The problem is that I don't want pagination for this. Is there a way to use filterer without pagination?

Not using `present_params`

I want to create a filterer that only returns results from all fields match. For example, let's say I want to get the results of only the records that both match the age and rank. If only age is given, it will return nothing. If only rank is given, it will return nothing.

I had thought of setting defaults to {age: nil, rank: nil} (yes, this will only work if neither of those fields can be nil), but noticed that present_params checks for values that are present?. This would also disallow people from searching for values that match "" (blank).

What issues would removing present_params cause? I did a cursory search in the git history but couldn't find the reason that method is there.

per_page causing error where string is compared to fixnum

This happens because per_page, when given in the params, is a string. I have a branch that fixes it here. I didn't create a pull request because there's no "0_4_x" branch to merge it into. Note: this branch is from v0.4.2. I took a quick look at master and I think master is susceptible to this issue too.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.