sortable_table.rb 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. require 'active_support/concern'
  2. module SortableTable
  3. extend ActiveSupport::Concern
  4. included do
  5. helper SortableTableHelper
  6. end
  7. protected
  8. def table_sort
  9. raise("You must call set_table_sort in any action using table_sort.") unless @table_sort_info.present?
  10. @table_sort_info[:order]
  11. end
  12. def set_table_sort(sort_options)
  13. valid_sorts = sort_options[:sorts] or raise ArgumentError.new("You must specify :sorts as an array of valid sort attributes.")
  14. default = sort_options[:default] || { valid_sorts.first.to_sym => :desc }
  15. if params[:sort].present?
  16. attribute, direction = params[:sort].downcase.split('.')
  17. unless valid_sorts.include?(attribute)
  18. attribute, direction = default.to_a.first
  19. end
  20. else
  21. attribute, direction = default.to_a.first
  22. end
  23. direction = direction.to_s == 'desc' ? 'desc' : 'asc'
  24. @table_sort_info = {
  25. order: { attribute.to_sym => direction.to_sym },
  26. attribute: attribute,
  27. direction: direction
  28. }
  29. end
  30. module SortableTableHelper
  31. # :call-seq:
  32. # sortable_column(attribute, default_direction = 'desc', name: attribute.humanize)
  33. def sortable_column(attribute, default_direction = nil, options = nil)
  34. if options.nil? && (options = Hash.try_convert(default_direction))
  35. default_direction = nil
  36. end
  37. default_direction ||= 'desc'
  38. options ||= {}
  39. name = options[:name] || attribute.humanize
  40. selected = @table_sort_info[:attribute].to_s == attribute
  41. if selected
  42. direction = @table_sort_info[:direction]
  43. new_direction = direction.to_s == 'desc' ? 'asc' : 'desc'
  44. classes = "selected #{direction}"
  45. else
  46. classes = ''
  47. new_direction = default_direction
  48. end
  49. link_to(name, url_for(sort: "#{attribute}.#{new_direction}"), class: classes)
  50. end
  51. end
  52. end