Module: ColumnSort::ColumnSortHelper

Defined in:
lib/column_sort/column_sort_helper.rb

Instance Method Summary collapse

Instance Method Details

Generates a link that sorts the page based on the current params

Parameters:

  • column_symbol (Symbol)

    The name of the sort column

  • column_name (String) (defaults to: nil)

    Display name for the sort column, defaults to the titlezed sort column

Returns:

  • (String)

    Link back to the current page with the new sorting parameters



26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
# File 'lib/column_sort/column_sort_helper.rb', line 26

def column_sort_link(column_symbol, column_name = nil)
  # default column name to column symbol titleized
  column_name = column_symbol.to_s.titleize if column_name.nil?

  # set default link attributes
  # note that we default to ascending search
  link_attributes = params.merge({
    :column_sort => { 
      :column => column_symbol, 
      :direction => "asc" 
    }
  })

  # start building the link text
  link_text = column_name
  if params[:column_sort].present?
    if params[:column_sort][:column].to_s == column_symbol.to_s
      # if sorting on the current column, add an arrow for the current direction and make the link sort in the opposite direction
      if params[:column_sort][:direction].to_s == "desc"
        link_text += '▼' # ▼
        link_attributes[:column_sort][:direction] = "asc"
      else
        link_text += '▲' # ▲
        link_attributes[:column_sort][:direction] = "desc"
      end 
    else
      # if not sorting on the current column, add a diamond and use the default sort direction
      link_text += ' ♦' # ♦
    end 
  else
    # if no sort is specified, add a diamond and use the default sort direction
    link_text += ' ♦' # ♦
  end 
  # return html string for an a tag with the correct request parameters
  link_to link_text.html_safe, link_attributes 
end

#set_default_column_sort(column, direction) ⇒ Object

Sets the default column sort for the view Updates the params directly

Parameters:

  • column (String or Symbol)

    The name of the sort column

  • column (String or Symbol)

    The direction of the sort



9
10
11
12
13
14
15
16
17
18
# File 'lib/column_sort/column_sort_helper.rb', line 9

def set_default_column_sort(column, direction)
  if params.present?
    if params[:column_sort].nil?
      params[:column_sort] = { 
        :column => column,
        :direction => direction
      }   
    end 
  end 
end