Module: OrderableHelper

Defined in:
lib/orderable2/orderable_helper.rb

Instance Method Summary collapse

Instance Method Details

#orderable_for(attr, options = {}) ⇒ Object



2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
# File 'lib/orderable2/orderable_helper.rb', line 2

def orderable_for(attr, options = {})
  label = I18n.t("orderable.#{attr}", default: attr.to_s.humanize)
  sort_params = params[:order] || ''

  this_clauses, other_clauses = sort_params.split(',').partition do |sort_param|
    sort_param.split(':').first == attr.to_s
  end

  this_clause = this_clauses.first
  this_clause ||= ''

  direction = this_clause.split(':').last

  if direction.nil?
    arrow = ''
    next_dir = "#{attr}:asc"
  elsif direction == 'asc'
    arrow = '↑'
    next_dir = "#{attr}:desc"
  elsif direction == 'desc'
    arrow = '↓'
    next_dir = ''
  else
    raise StandardError, direction
  end
  label = label + ' ' + arrow

  if options[:single]
    new_order = [next_dir]
  else
    new_order = other_clauses + [next_dir]
  end

  link_to label.html_safe, request.query_parameters.merge(order: new_order.join(','))
end