Project

serpentine

0.0
No commit activity in last 3 years
No release in over 3 years
Easy query parameter filters for Rails applications
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
 Dependencies

Development

Runtime

~> 3
 Project Readme

Serpentine

Build Status Gem Version Code Climate Dependency Status

Serpentine makes complicated query parameters easy. This is a very commong problem in rails applications. Your controller needs to accept a variety of input parameters to filter/order/search a collection in some way. It's not hard to write this logic, but god damn it is a pain in the ass. It's just a lot of worthless conditional programming. Serpentine makes this easier.

Usage

class PostsController < ApplicationController
  filter_collection :alphabetically
  filter_collection :by_ids, :if => proc { |params| params[:ids] }

  # apply_scopes! is added by Serpentine. You can call it yourself
  # in your own actions if you like.
  before_filter :apply_scopes!, :only => :index

  # define a collection accessor
  # It is important to use ||= here
  # otherwise Post.unscoped will *always* be passed into
  # the next filter
  def collection
    @collection ||= Post.unscoped
  end

  def index
    respond_with @collection
  end

  private

  # define methods declared in filters
  def alphabetically
    collection.alphabetically
  end

  def by_ids
    collection.where :id => params[:ids]
  end
end

More Examples

class PostsController < ApplicationController
  filter_collection :method_name, :if => proc { |params| }
  filter_collection :method_name, :if => :name_of_method
  filter_collection :method_name, :unless => proc { |params| }
  filter_collection :method_name, :unless => :name_of_method
  filter_collection :method_name

  def collection
    @collection ||= Post.unscoped
  end

  def index
    apply_scopes!

    # collection now has all the different filters applied

    do_more_logic_on collection

    respond_with collection
  end
end

And that's it! This will keep the real logic outside of your actions. This make it trivially easy to add more filters. Filters are inheritable. You can define filters in ApplicationController and they will be passed down to all other subclasses.