Project

sortify

0.0
No commit activity in last 3 years
No release in over 3 years
Sortify acts as a wrapper around ActiveRecord scopes, providing a tiny bit of extra functionality to keep track of valid sorting options and call them from user input.
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
 Dependencies

Development

Runtime

 Project Readme

Sortify

Gem Version Build Status Code Climate Coverage Status Dependency Status Documentation Status

Sortify helps you handle user-provided sort options in Rails apps.

⚠️ Warning:

Sortify is in the very early stages of development right now, has few tests and could introduce breaking changes. Use at your own risk.

Getting Started

To get started, add sortify to your gemfile:

gem 'sortify'

Then run bundle install to fetch the current version.

Usage

Using Sortify is very simple. All you need to do is specify sorting options in your models, then call sortify in your controllers naming a sorting option.

Models

Sortify acts as a wrapper around ActiveRecord scopes, providing a tiny bit of extra functionality to keep track of valid sorting options.

If you don't know what scopes are, you can read about them here:

First you'll need to extend Sortify, and then you can specify your sort options.

class Item < ActiveRecord::Base
  extend Sortify # includes the sortify methods in your model

  default_sort_option :most_recent
  sort_option :most_recent, -> { order(updated_at: :desc) }
  sort_option :created_first, -> { order(created_at: :asc) }
end

sort_option takes a symbol as a name, and a lambda, exactly like an ActiveRecord scope.

You can optionally provide a default_sort_option which specifies which sort to use in the event that the user-specified sort is invalid or absent.

Controllers

For your controllers, Sortify provides the sortify method, which takes a string naming one of your sort options as an argument. Because Sortify uses scopes under the hood, it can be chained with other scopes.

⚠️ Warning:

The sortify method will raise a NoMethodError if it cannot find a sorting option with the name you passed in unless a valid default is specified.

class ItemController < ApplicationController
  def index
    @items = Item.sortify("most_recent") # sorts your items by most recent
    @others = Item.sortify(params[:sort]) # sorts by the method specified in the params
  end
end

Because it uses scopes under the hood, Sortify also provides separate methods for your sorting options:

class ItemController < ApplicationController
  def index
    @items = Item.created_first # all of your Items, sorted by creation date
  end
end

License

Sortify is released under the MIT License