Class: SortHelper::SortCriteria

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

Instance Method Summary collapse

Constructor Details

#initializeSortCriteria



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

def initialize
  @criteria = []
end

Instance Method Details

#add(*args) ⇒ Object



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

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

#add!(key, asc) ⇒ Object



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

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

#available_criteria=(criteria) ⇒ Object



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

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



86
87
88
89
# File 'app/helpers/sort_helper.rb', line 86

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

#empty?Boolean



124
125
126
# File 'app/helpers/sort_helper.rb', line 124

def empty?
  @criteria.empty?
end

#first_asc?Boolean



120
121
122
# File 'app/helpers/sort_helper.rb', line 120

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

#first_keyObject



116
117
118
# File 'app/helpers/sort_helper.rb', line 116

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

#from_param(param) ⇒ Object



81
82
83
84
# File 'app/helpers/sort_helper.rb', line 81

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

#to_paramObject



91
92
93
# File 'app/helpers/sort_helper.rb', line 91

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

#to_sqlObject



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

def to_sql
  sql = @criteria.collect do |k,o|
    if s = @available_criteria[k]
      (o ? s.to_a : s.to_a.collect {|c| append_desc(c)}).join(', ')
    end
  end.compact.join(', ')
  sql.blank? ? nil : sql
end