Skip to content

Instantly share code, notes, and snippets.

@spovich
Created August 10, 2011 18:30
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save spovich/1137716 to your computer and use it in GitHub Desktop.
Save spovich/1137716 to your computer and use it in GitHub Desktop.
def sort_link(attribute, *args)
attr_name = attribute.to_s
name = (args.size > 0 && !args.first.is_a?(Hash)) ? args.shift.to_s : attr_name.humanize
prev_attr, prev_order = params['q'].nil? ? '' '' : params['q']['s'].to_s.split(' ')
options = args.first.is_a?(Hash) ? args.shift : {}
current_order = prev_attr == attr_name ? prev_order : nil
if options[:default_order] == :desc
new_order = current_order == 'desc' ? 'asc' : 'desc'
else
new_order = current_order == 'asc' ? 'desc' : 'asc'
end
options.delete(:default_order)
html_options = args.first.is_a?(Hash) ? args.shift : {}
css = ['sort_link', current_order].compact.join(' ')
html_options[:class] = [css, html_options[:class]].compact.join(' ')
q = params['q'].nil? ? {} : params['q'].dup
q.merge!(:s => "#{attr_name} #{new_order}")
options.merge!(:q => q)
link_to [ERB::Util.h(name), order_indicator_for(current_order)].compact.join(' ').html_safe,
url_for(options),
html_options
end
def order_indicator_for(order)
if order == 'asc'
'▲'
elsif order == 'desc'
'▼'
else
nil
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment