Module SortHelper
In: sort_helper.rb

sort_helper.rb - SortHelper for Ruby on Rails

Author: Dave Burt dave@burt.id.au

Version: 17 Feb 2005

Makes column headings users can click to define how the table is sorted.

Example

View

 <tr>
   <th><%= link_to_sort_by 'First Name', 'name' %></th>
   <th><%= link_to_sort_by 'Surname', 'family.name' %></th>
   <th><%= link_to_sort_by 'Email', 'email' %></th>
 </tr>

Controller:

 helper :sort

 def list  # action
   SortHelper.columns = %w[
     name
     family.name
     email
   ]
   SortHelper.default_order = %w[family.name name]
   @people = Person.find_all.sort do |a, b|
     SortHelper.sort(a, b, @params)
   end
 end

Methods

Public Class methods

Set the columns that may be used to sort by. You must set this from the controller before you can use link_to_sort_by in a view.

Set the columns that are used to sort by default

This is a comparison method that returns -1, 0 or 1 depending on the passed objects a and b, and the sorting priorities defined in params. It can be used in blocks given to +Enumerable#sort+.

Use it like this:

 @people = Person.find_all.sort do |a, b|
   SortHelper.sort(a, b, @params)
 end

Public Instance methods

Create a link (‘a’ tag) back to the current action, but sorting by sort_column before any existing ordering.

Example: On an un-sorted page,

 <%= link_to_sort_by 'First Name', 'name' %>
 <%= link_to_sort_by 'Surname', 'family.name' %>
 <%= link_to_sort_by 'Email', 'email' %>

could result in:

 <a href="/person/list?sort=1">First Name</a>
 <a href="/person/list?sort=2">Surname</a>
 <a href="/person/list?sort=3">Email</a>

If the page was already sorted by first name,

 <%= link_to_sort_by 'First Name', 'name' %>
 <%= link_to_sort_by 'Surname', 'family.name' %>
 <%= link_to_sort_by 'Email', 'email' %>

could result in:

 <a href="/person/list?sort=-1">First Name</a>
 <a href="/person/list?sort=2+1">Surname</a>
 <a href="/person/list?sort=3+1">Email</a>

[Validate]