Class: SortHelper::SortCriteria

Inherits:
Object
  • Object
show all
Defined in:
app/helpers/sort_helper.rb

Instance Method Summary collapse

Constructor Details

#initializeSortCriteria

Returns a new instance of SortCriteria



58
59
60
# File 'app/helpers/sort_helper.rb', line 58

def initialize
  @criteria = []
end

Instance Method Details

#add(*args) ⇒ Object



104
105
106
107
108
# File 'app/helpers/sort_helper.rb', line 104

def add(*args)
  r = self.class.new.from_param(to_param)
  r.add!(*args)
  r
end

#add!(key, asc) ⇒ Object



98
99
100
101
102
# File 'app/helpers/sort_helper.rb', line 98

def add!(key, asc)
  @criteria.delete_if {|k,o| k == key}
  @criteria = [[key, asc]] + @criteria
  normalize!
end

#available_criteria=(criteria) ⇒ Object



62
63
64
65
66
67
# File 'app/helpers/sort_helper.rb', line 62

def available_criteria=(criteria)
  unless criteria.is_a?(Hash)
    criteria = criteria.inject({}) {|h,k| h[k] = k; h}
  end
  @available_criteria = criteria
end

#criteria=(arg) ⇒ Object



74
75
76
77
# File 'app/helpers/sort_helper.rb', line 74

def criteria=(arg)
  @criteria = arg
  normalize!
end

#empty?Boolean

Returns:

  • (Boolean)


118
119
120
# File 'app/helpers/sort_helper.rb', line 118

def empty?
  @criteria.empty?
end

#first_asc?Boolean

Returns:

  • (Boolean)


114
115
116
# File 'app/helpers/sort_helper.rb', line 114

def first_asc?
  @criteria.first && @criteria.first.last
end

#first_keyObject



110
111
112
# File 'app/helpers/sort_helper.rb', line 110

def first_key
  @criteria.first && @criteria.first.first
end

#from_param(param) ⇒ Object



69
70
71
72
# File 'app/helpers/sort_helper.rb', line 69

def from_param(param)
  @criteria = param.to_s.split(',').collect {|s| s.split(':')[0..1]}
  normalize!
end

#to_aObject



94
95
96
# File 'app/helpers/sort_helper.rb', line 94

def to_a
  @criteria.dup
end

#to_paramObject



79
80
81
# File 'app/helpers/sort_helper.rb', line 79

def to_param
  @criteria.collect {|k,o| k + (o ? '' : ':desc')}.join(',')
end

#to_sqlObject

Returns an array of SQL fragments used to sort the list



84
85
86
87
88
89
90
91
92
# File 'app/helpers/sort_helper.rb', line 84

def to_sql
  sql = @criteria.collect do |k,o|
    if s = @available_criteria[k]
      s = [s] unless s.is_a?(Array)
      s.collect {|c| append_order(c, o ? "ASC" : "DESC")}
    end
  end.flatten.compact
  sql.blank? ? nil : sql
end