Skip to content
This repository

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
branch: master

Fetching latest commit…

Octocat-spinner-32-eaf2f5

Cannot retrieve the latest commit at this time

Octocat-spinner-32 lib
Octocat-spinner-32 script
Octocat-spinner-32 test
Octocat-spinner-32 .gitignore Don't track Gemfile.lock June 22, 2012
Octocat-spinner-32 .travis.yml
Octocat-spinner-32 Gemfile
Octocat-spinner-32 MIT-LICENSE
Octocat-spinner-32 Rakefile
Octocat-spinner-32 readme.md
Octocat-spinner-32 serpentine.gemspec
readme.md

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.

Something went wrong with that request. Please try again.