There are always some options for your page. Perhaps the number of items to display (articles, picture, projects, …). Or the sort key for those. Preferably you set some sane defaults. But you’d like to enable your visitors to change those?

This is what I did first so people could change the sort order:

lengthy RHTML code for option switches

1
2
3
4
sort by <%= link_to_if(session[:tag_sort] == 'alpha',
                       'alpha', '?settagsort=alpha') %> |
<%= link_to_if(session[:tag_sort] == 'freq',
               'freq', '?settagsort=freq') %>.

That way a link to the current sort order will be suppresed and you get the visual impresion of flipping a switch.

Remember DRY? Ain’t looking much like it as you keep adding options…

Application helpers to the rescue!

application helper for option switches

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
  def link_to_switch(parameter, name,
                     html_options = {},
                     *parameters_for_method_reference,
                     &block)
    html_param = 'set' + parameter.to_s.delete('_')
    link_to_unless(session[parameter] == name, name,
                   '?'+html_param+'='+name,
                   html_options,
                   *parameters_for_method_reference,
                   &block)
  end

Put this function in your application_helper.rb (its not that lengthy if you ignore the last three arguments, they just add full compatibility to the link_to’s arguments).

Then call it this way:

nice RHTML for option switches

1
2
3
4
5
6
sort by <%= link_to_switch(:tag_sort, 'alpha') %> |
        <%= link_to_switch(:tag_sort, 'freq') %>.

hide minimum: <%= link_to_switch(:min_posts, '1') %>,
              <%= link_to_switch(:min_posts, '2') %>,
              <%= link_to_switch(:min_posts, '5') %>.

And in your controller you would be doing something like this

reading the options in your controller

1
2
3
  session[:min_posts] = params[:setminposts] unless
                        params[:setminposts].nil?
  session[:min_posts] ||= 1

Happy optionizing…!