I spent a little time this week pulling sorting out of a project of mine as a gem. I’m really happy with where I got to with it.
What this is is something that lets you very easily add column sorting to your data views so that visitors can click on the column headings to re-present the data sorted by that heading.
There are two parts to this gem:
The Model
You get the declarative sort_on method for your model so you can stipulate in your model which attributes are allowed to be sorted on. This means that sorting is always a positive assertion, so (for example) you can choose to select only those attributes that map to columns in your DB that you have indexes for.
If sorting is attempted for any other columns, then an exception is thrown.
You also get the class method sort_by which takes a parameter (string or symbol) that has to be one of the attributes declared in that model’s sort_on and returns a hash suitable for merging into parameters for an ActiveRecord find.
The View
You also get a helper for outputting the headers in the view called sort_headers_for which makes it really easy to output all the gracefully degrading AJAX-enabled headers/links for sorting your list.
Let’s Have a Look
I’ve pretty much just chomped this out of the gem’s README, but it’s a decent example:
app/models/author.rb
sort_on :name, :updated_at
app/controllers/site_controller.rb
def index
@authors = Author.all( Author.sort_by(params[:sort]) )
if request.xhr?
return render :partial => 'authors'
end
end
app/views/site/index.html.erb
<div id="authors">
<%= render :partial => 'authors' %>
</div>
app/views/site/_authors.html.erb
<table>
<thead>
<tr>
<%
sort_headers_for :author, %w{name ranking phone updated_at} do |header|
"Last Changed" if header == 'updated_at'
end
%>
</tr>
</thead>
<tbody>
<% @authors.each do |author| -%>
<tr>
<td><%=h author.name %></td>
<td><%=h author.ranking %></td>
<td><%=h author.phone %></td>
<td><%=h author.updated_at %></td>
</tr>
<% end -%>
</tbody>
</table>
Now the sort_headers_for method is using a lot of convention in there for the code that it’s generating, but the good news is that virtually everything can be overridden if you want to do things differently.
Hope you enjoy, you can get the gem here or just install with sudo gem install JasonKing-good_sort


Comments
There are 0 comments on this post. Post yours →
Post a comment
Required fields look like this.