To check out this repository please hg clone the following URL, or open the URL using EasyMercurial or your preferred Mercurial client.

Statistics Download as Zip
| Branch: | Tag: | Revision:

root / app / helpers / sort_helper.rb @ 1330:441b66f148b6

History | View | Annotate | Download (6.18 KB)

1
# encoding: utf-8
2
#
3
# Helpers to sort tables using clickable column headers.
4
#
5
# Author:  Stuart Rackham <srackham@methods.co.nz>, March 2005.
6
#          Jean-Philippe Lang, 2009
7
# License: This source code is released under the MIT license.
8
#
9
# - Consecutive clicks toggle the column's sort order.
10
# - Sort state is maintained by a session hash entry.
11
# - CSS classes identify sort column and state.
12
# - Typically used in conjunction with the Pagination module.
13
#
14
# Example code snippets:
15
#
16
# Controller:
17
#
18
#   helper :sort
19
#   include SortHelper
20
#
21
#   def list
22
#     sort_init 'last_name'
23
#     sort_update %w(first_name last_name)
24
#     @items = Contact.find_all nil, sort_clause
25
#   end
26
#
27
# Controller (using Pagination module):
28
#
29
#   helper :sort
30
#   include SortHelper
31
#
32
#   def list
33
#     sort_init 'last_name'
34
#     sort_update %w(first_name last_name)
35
#     @contact_pages, @items = paginate :contacts,
36
#       :order_by => sort_clause,
37
#       :per_page => 10
38
#   end
39
#
40
# View (table header in list.rhtml):
41
#
42
#   <thead>
43
#     <tr>
44
#       <%= sort_header_tag('id', :title => 'Sort by contact ID') %>
45
#       <%= sort_header_tag('last_name', :caption => 'Name') %>
46
#       <%= sort_header_tag('phone') %>
47
#       <%= sort_header_tag('address', :width => 200) %>
48
#     </tr>
49
#   </thead>
50
#
51
# - Introduces instance variables: @sort_default, @sort_criteria
52
# - Introduces param :sort
53
#
54

    
55
module SortHelper
56
  class SortCriteria
57

    
58
    def initialize
59
      @criteria = []
60
    end
61

    
62
    def available_criteria=(criteria)
63
      unless criteria.is_a?(Hash)
64
        criteria = criteria.inject({}) {|h,k| h[k] = k; h}
65
      end
66
      @available_criteria = criteria
67
    end
68

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

    
74
    def criteria=(arg)
75
      @criteria = arg
76
      normalize!
77
    end
78

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

    
83
    def to_sql
84
      sql = @criteria.collect do |k,o|
85
        if s = @available_criteria[k]
86
          (o ? s.to_a : s.to_a.collect {|c| append_desc(c)}).join(', ')
87
        end
88
      end.compact.join(', ')
89
      sql.blank? ? nil : sql
90
    end
91

    
92
    def to_a
93
      @criteria.dup
94
    end
95

    
96
    def add!(key, asc)
97
      @criteria.delete_if {|k,o| k == key}
98
      @criteria = [[key, asc]] + @criteria
99
      normalize!
100
    end
101

    
102
    def add(*args)
103
      r = self.class.new.from_param(to_param)
104
      r.add!(*args)
105
      r
106
    end
107

    
108
    def first_key
109
      @criteria.first && @criteria.first.first
110
    end
111

    
112
    def first_asc?
113
      @criteria.first && @criteria.first.last
114
    end
115

    
116
    def empty?
117
      @criteria.empty?
118
    end
119

    
120
    private
121

    
122
    def normalize!
123
      @criteria ||= []
124
      @criteria = @criteria.collect {|s| s = s.to_a; [s.first, (s.last == false || s.last == 'desc') ? false : true]}
125
      @criteria = @criteria.select {|k,o| @available_criteria.has_key?(k)} if @available_criteria
126
      @criteria.slice!(3)
127
      self
128
    end
129

    
130
    # Appends DESC to the sort criterion unless it has a fixed order
131
    def append_desc(criterion)
132
      if criterion =~ / (asc|desc)$/i
133
        criterion
134
      else
135
        "#{criterion} DESC"
136
      end
137
    end
138
  end
139

    
140
  def sort_name
141
    controller_name + '_' + action_name + '_sort'
142
  end
143

    
144
  # Initializes the default sort.
145
  # Examples:
146
  #
147
  #   sort_init 'name'
148
  #   sort_init 'id', 'desc'
149
  #   sort_init ['name', ['id', 'desc']]
150
  #   sort_init [['name', 'desc'], ['id', 'desc']]
151
  #
152
  def sort_init(*args)
153
    case args.size
154
    when 1
155
      @sort_default = args.first.is_a?(Array) ? args.first : [[args.first]]
156
    when 2
157
      @sort_default = [[args.first, args.last]]
158
    else
159
      raise ArgumentError
160
    end
161
  end
162

    
163
  # Updates the sort state. Call this in the controller prior to calling
164
  # sort_clause.
165
  # - criteria can be either an array or a hash of allowed keys
166
  #
167
  def sort_update(criteria, sort_name=nil)
168
    sort_name ||= self.sort_name
169
    @sort_criteria = SortCriteria.new
170
    @sort_criteria.available_criteria = criteria
171
    @sort_criteria.from_param(params[:sort] || session[sort_name])
172
    @sort_criteria.criteria = @sort_default if @sort_criteria.empty?
173
    session[sort_name] = @sort_criteria.to_param
174
  end
175

    
176
  # Clears the sort criteria session data
177
  #
178
  def sort_clear
179
    session[sort_name] = nil
180
  end
181

    
182
  # Returns an SQL sort clause corresponding to the current sort state.
183
  # Use this to sort the controller's table items collection.
184
  #
185
  def sort_clause()
186
    @sort_criteria.to_sql
187
  end
188

    
189
  def sort_criteria
190
    @sort_criteria
191
  end
192

    
193
  # Returns a link which sorts by the named column.
194
  #
195
  # - column is the name of an attribute in the sorted record collection.
196
  # - the optional caption explicitly specifies the displayed link text.
197
  # - 2 CSS classes reflect the state of the link: sort and asc or desc
198
  #
199
  def sort_link(column, caption, default_order)
200
    css, order = nil, default_order
201

    
202
    if column.to_s == @sort_criteria.first_key
203
      if @sort_criteria.first_asc?
204
        css = 'sort asc'
205
        order = 'desc'
206
      else
207
        css = 'sort desc'
208
        order = 'asc'
209
      end
210
    end
211
    caption = column.to_s.humanize unless caption
212

    
213
    sort_options = { :sort => @sort_criteria.add(column.to_s, order).to_param }
214
    url_options = params.merge(sort_options)
215

    
216
     # Add project_id to url_options
217
    url_options = url_options.merge(:project_id => params[:project_id]) if params.has_key?(:project_id)
218

    
219
    link_to_content_update(h(caption), url_options, :class => css)
220
  end
221

    
222
  # Returns a table header <th> tag with a sort link for the named column
223
  # attribute.
224
  #
225
  # Options:
226
  #   :caption     The displayed link name (defaults to titleized column name).
227
  #   :title       The tag's 'title' attribute (defaults to 'Sort by :caption').
228
  #
229
  # Other options hash entries generate additional table header tag attributes.
230
  #
231
  # Example:
232
  #
233
  #   <%= sort_header_tag('id', :title => 'Sort by contact ID', :width => 40) %>
234
  #
235
  def sort_header_tag(column, options = {})
236
    caption = options.delete(:caption) || column.to_s.humanize
237
    default_order = options.delete(:default_order) || 'asc'
238
    options[:title] = l(:label_sort_by, "\"#{caption}\"") unless options[:title]
239
    content_tag('th', sort_link(column, caption, default_order), options)
240
  end
241
end
242