Module: Toolbox::Sorting

Defined in:
lib/toolbox/sorting.rb

Class Method Summary collapse

Class Method Details

.current(params, prefix, field_name) ⇒ Object

Get the current sorting direction from the given params hash



44
45
46
47
48
49
50
51
# File 'lib/toolbox/sorting.rb', line 44

def self.current(params, prefix, field_name) #:nodoc:
  dir = nil
  if val = params[params_key(prefix)]
    f, d = val.split '-'
    dir = fix_direction(d) if f == field_name
  end
  dir
end

.fix_direction(dir) ⇒ Object

inhibit any sql injection



39
40
41
# File 'lib/toolbox/sorting.rb', line 39

def self.fix_direction dir #:nodoc:
  dir == 'asc' ? 'asc' : (dir == 'desc' ? 'desc' : 'none')
end

.order_by(params, widgets, prefix = nil) ⇒ Object

Create an oder-by string Parameters

  • prefix: an optional prefix used to get the right sort-field from the params hash

  • params: the parameter hash

  • widgets: an array of field configuration



17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
# File 'lib/toolbox/sorting.rb', line 17

def self.order_by(params, widgets, prefix = nil)
  val = params[params_key(prefix)]
  return nil unless val # no sort parameter set
  field, dir = val.split '-'
  dir = fix_direction dir
  return nil if dir == 'none' # no sort direction
  # find the field in field list
  field = widgets.select{ |w| w == field }.first
  order_by_string = nil
  if field
    if field.order_by
      order_by_string = field.order_by
      order_by_string = order_by_string.join(" #{dir}, ") if order_by_string.is_a? Array
    else
      order_by_string = quote_order_by(field.model_name.tableize, field.name.to_s)
    end
    order_by_string += " #{dir}"
  end
  order_by_string
end

.params(params, prefix, field_name, new_dir) ⇒ Object

Gets a parameter hash for link generation



54
55
56
57
58
59
60
61
# File 'lib/toolbox/sorting.rb', line 54

def self.params(params, prefix, field_name, new_dir) #:nodoc:
  if new_dir
    params.merge({params_key(prefix) => "#{field_name}-#{new_dir}"})
  else
    params.delete params_key(prefix)
    params
  end
end

.params_key(prefix) ⇒ Object

Get the sort-key for the params hash regarding the prefix



64
65
66
67
68
69
70
# File 'lib/toolbox/sorting.rb', line 64

def self.params_key(prefix) #:nodoc:
  if prefix
    "#{prefix}-sort".to_sym
  else
    :sort
  end
end

.quote_order_by(table, field) ⇒ Object



6
7
8
9
10
# File 'lib/toolbox/sorting.rb', line 6

def self.quote_order_by(table, field)
  table = ActiveRecord::Base.connection.quote_table_name(table)
  field = ActiveRecord::Base.connection.quote_column_name(field)
  "#{table}.#{field}"
end