Skip to content

Instantly share code, notes, and snippets.

@mynameisrufus
Created July 13, 2010 03:26
Show Gist options
  • Save mynameisrufus/473415 to your computer and use it in GitHub Desktop.
Save mynameisrufus/473415 to your computer and use it in GitHub Desktop.
class User < ActiveRecord::Base
scope :order, lambda{|params|
return if params.nil?
order = []
params.split(/\|/).each do |param|
order << param.gsub(/_asc/, ' ASC').gsub(/_desc/, ' DESC')
end
{:order => order.join(' ,')}
}
end
module UsersHelper
def order(attribute)
order_first = "#{attribute.to_s}_asc"
order_rest = []
if params[:order].present?
params[:order].split(/\|/).each do |param|
param.match(/(\w+)_(asc|desc)/) do |match_data|
if match_data[1] == attribute.to_s
order_first = "#{attribute.to_s}_#{reverse(match_data[2])}"
else
order_rest << param
end
end
end
end
{:order => order_rest.unshift(order_first).join('|'), :page => params[:page], :per_page => params[:per_page]}
end
def reverse(order)
case order
when 'asc'
'desc'
when 'desc'
'asc'
else
'asc'
end
end
end
<th><%= link_to 'name', users_path(order(:name)) %></th>
<th><%= link_to 'email', users_path(order(:email)) %></th>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment