LRBlog

Logical Reality Design: Web Design and Software Development

Archive for June, 2008

Getting <select> options in the right order

June 23, 2008

Sometimes you may want to generate a selector with a fixed set of options.   In one recent task of mine, we needed a selector for an integer 1 through 10, but the client wanted them labeled also with text to identify how the numbers mapped to the words “High” “Medium” and “Low”. (We were selecting the priority level of a task in a project management application). Essentially, I want to generate this HTML output:


<select id="task_priority" name="task[priority]"> 
    <option value="1">1 - High</option> 
    <option value="2">2 - High</option> 
    <option value="3">3 - High</option> 
    <option value="4">4 - Med</option> 
    <option selected="selected" value="5">5 - Med</option> 
    <option value="6">6 - Med</option> 
    <option value="7">7 - Med</option> 
    <option value="8">8 - Low</option> 
    <option value="9">9 - Low</option> 
    <option value="10">10 - Low</option>
</select>

These are fixed name/value pairs, so it made sense to me to store them as a constant hash in my Task model:

Hash in Task.rb


PRIORITY_OPTIONS = { "1 - High" =&gt; "1", "2 - High" =&gt; "2", "3 - High" =&gt; "3",
"4 - Med" =&gt; "4", "5 - Med" =&gt; "5", "6 - Med" =&gt; "6", "7 - Med" =&gt; "7",
"8 - Low" =&gt; "8", "9 - Low" =&gt; "9", "10 - Low" =&gt; "10"  }

However, I was rather dismayed to discover that this didn’t produce the results I wanted, because Ruby hashes (in Ruby 1.8.6) do not preserve order. This is what came out:

Badly ordered priority selector

That’s not what I wanted! I knew that select will also take arrays, but of course I needed separate name/value pairs, which I can’t get with just straight arrays. I spent a while playing around with OrderedHash, which exists in Rails but is essentially undocumented and, as it turns out, does not support any useful functions of Hash like merge! and insert! that might make it easy to construct my list of options.

The Fix: Array of Arrays, or Array of Hashes

The documentation is not entirely clear on this, but if you send an array of 2-element arrays to select, rails will use the two elements of each inner array as if they were key and value pairs, and because the entire structure is an array it will preserve order. So, to get the results I wanted, I just need to change my constant to this:

PRIORITY_OPTIONS = [ ["1 - High", 1], ["2 - High", 2], ["3 - High", 3],
["4 - Med", 4], ["5 - Med", 5], ["6 - Med", 6], ["7 - Med", 7],
["8 - Low", 8], ["9 - Low", 9], ["10 - Low", 10] ]

And I get the result I was looking for :

Correctly ordered select options.

As it turns out, the way ActionView processes the options is fairly general: if you pass it any enumerable object, it will iterate that object, and for each element will check to see if that element supports the methods :first and :last (and isn’t a string). If so, it will generate an option with the text set to element.first and the value set to element.last. If it was a string, or didn’t support first and last, both the text and value of the option are set to the element itself.

Testing it

Here’s a handy function I use for testing it the presence of a selector. You pass it the name of your selector, the name of hash or array of options (in the any format supported by select), and optionally the value of an item that should be pre-selected, and it will assert the existence of each of those things. If you need to handle selectors with multiple selections, you can just wrap the last assertion in a loop.

Drop this in test/test_helper.rb

  # Assert existence of form select input
  # the <option> tags can be passed either as 
  # a hash like this: {'foo'=>'bar', 'baz'=>'qux'} 
  # or an array of arrays like this: [ ['foo', 'bar'], ['baz', 'qux'] ]  
  # either will be asserted to match:
  #         <option value='bar'>foo</option>
  #         <option value='qux'>baz</option>
  # or as an array like this:
  #   [ 'foo', 'bar' ] will be asserted to match
  #         <option value='foo'>foo</option>
  #         <option value='bar'>bar</option>
  def assert_select_input(name, option_values, options={})
    attributes = { :name => name }

    # first assert that the select tag exists
    selector = { :tag => "select", :attributes => attributes }
    assert_tag selector   
        
    option_values.each do | opt |
      if !opt.is_a?(String) and opt.respond_to?(:first) and opt.respond_to?(:last)
        assert_tag({:tag => "option", :attributes => { :value => opt.last },      
          :parent => selector, :content => opt.first })
      else
        assert_tag({:tag => "option", :attributes => { :value => opt },      
          :parent => selector, :content => opt })               
      end
    end        
    
    # check for the pre-selected option, if any
    if options[:selected] 
      assert_tag :tag => "option", :attributes => {:selected => 'selected', 
        :value => options[:selected] }
    end    
  end  

As an example of how to use it, here’s my method for testing the task priority selector pictured above:

  # asserts a <SELECT> field, targeting task[priority], containing ten
  # appropriately formatted <OPTIONS>, and with selected_num (if any) the
  # pre-selected option
  def assert_priority_select(selected_num = nil)
    options = selected_num ? { :selected => selected_num } : Hash.new
    assert_select_input "task[priority]", Task::PRIORITY_OPTIONS, options  
  end

Where the array specified in the Task model looks like this:

  PRIORITY_OPTIONS = [ ["1 - High", 1], ["2 - High", 2], ["3 - High", 3], 
    ["4 - Med", 4], ["5 - Med", 5], ["6 - Med", 6], ["7 - Med", 7],
    ["8 - Low", 8], ["9 - Low", 9], ["10 - Low", 10] ]

Using redirect_to :back to improve user interfaces

June 18, 2008

It’s a scourge that inflicts nearly every website: the dreaded empty page stating “Your search returned no results.” Or even worse, the search results page with a header “Search results” and zero content, the footer immediately following the header. This is not only useless, but also confusing to the user, because it takes the reader several seconds to even realize that the search returned no results.

For example, I just got this one on the otherwise lovely workingwithrails.com when I searched for RoR developers in Pasadena, CA:

A search results page with no results!

This is lame, lame, lame. A search results page with no results is guaranteed not to be useful to the user! From a user interface perspective, it’s akin to redirecting a user to a login page after they try to access some resource, and then sending them back to the front page or a super-lame “thank you for logging in” page afterwards.    The user should always see a useful page, and should never have to waste clicks getting back to what they wanted.

It’s not only bad UI, it’s also entirely unnecessary, because in Rails you can fix this for good with two lines of code.

Avoid wasted pages and annoyed users with redirect_to: back

If your user’s search doesn’t find anything, don’t make them waste their time at a whole page that tells them only that.  Instead just send them straight back to the search page.  Better yet, redirect them back to wherever they came from, since they might well be able to invoke search from any number of different contexts in your application. You don’t need a whole page to tell them the search didn’t find anything - a flash notice is more than sufficient:

Redirecting back with a flash after an empty search:

def search
  @results = YourModel.execute_some_search(params[:some_parameter]);
  if @results.size == 0
    flash[:notice] = "No items found matching '#{params[:some_parameter]}'"
    redirect_to :back
  end
end

Testing redirect_to :back

Testing redirect_to :back isn’t completely trivial, because of course there’s no previous page when you render a page in a test context. So, when you try to run a controller that redirects back, you’ll see an error. The easiest thing to do is to artificially set a previous page. I have these two methods in test/test_helper.rb:

def fake_referer
    @request.env['HTTP_REFERER'] = 'http://previous_page'
  end
  
  def assert_redirected_back
    assert_redirected_to 'http://previous_page'
  end

Then anytime I am working on a controller that involves back redirects, I drop fake_referrer in my setup method and then use assert_redirected_back. For example, in a search controller test (this is from a controller that has an action called ‘contents’ for searching items by text content - the search itself uses ferret):

def setup
    super
    fake_referer
  end

  def test_contents_search_fails
    get :contents, :contents => "some&junk*that(will@never)match$anything"
    assert_not_nil flash[:notice]
    assert_redirected_back
  end

Firefox Download Day (= display: inline-block day!)

June 18, 2008

It’s Firefox 3 Download Day!   Go get it, please.

I am excited about this, but perhaps not for the same reason most other people were. I am excited because Firefox 3 is the first version to implement the CSS rule “display: inline-block”. Inline-block allows you to generate chunks of content of rectangular shape that will flow inline in your content (like text, images, or tables) but whose contents act like a block, and whose borders and margins are respected in the flow.

Let’s make it clear what I mean.

The beauty and versatility of display: inline-block

Setting a CSS element’s display: property to inline-block tells the browser to treat the element as a rectangular block, with internal flow just like any other block, and to respect the padding, border, and margins, but to flow that rectangle with other inline content - exactly the way the browser would flow an image. In addition, you can specify the width and height of inline-block items. This is a crazy useful concept from a layout perspective: it would allow you to make buttons out of text that lay out horizontally, or to layer images on top of each other inside a small span or div.

Here’s an example of a series of list items set with border, padding, and a width and height. The code first:

<style>
      ul {
        width: 400px;
        border: 2px solid black;
        background: #aaf;
      }
      li {
        border: 2px dotted blue;
        padding: 1em;      
        width: 100px;
        height: 35px;
      }
      ul.inline li {
        display: inline;
      }
      ul.inline-block li {
        display: inline-block;
      }
    </style>
<h2>Padded words wrapped with display: inline;</h2>
  <p>
    <ul class="inline">
    <li>Lorem</li>
    <li>ipsum</li>
    <li>dolor</li>
    <li>sit</li>    
    <li>amet</li>
    <li>consectetur</li>
    <li>adipisicing</li>
    <li>elit</li>    
    <li>sed</li>
    <lido</li>
    <li>eiusmod</li>
    </ul>
  </p>

  <h2>Padded words wrapped with display: inline-block;</h2>
  <p>
    <ul class="inline-block">
    <li>Lorem</li>
    <li>ipsum</li>
    <li>dolor</li>
    <li>sit</li>    
    <li>amet</li>
    <li>consectetur</li>
    <li>adipisicing</li>
    <li>elit</li>    
    <li>sed</li>
    <li>do</li>
    <li>eiusmod</li>
    </ul>
  </p>

Here’s how Safari renders the above code (correctly):

And here’s how Firefox 2 renders it (incorrectly):

Horrific - FF2 simply ignores inline-block, causing the list elements to render in their default display mode, block. What’s galling about this is that for several years Firefox has been the only browser that gets it wrong! That’s right, even Internet Explorer 6 gets this right … at least on some elements, specifically those that are natively display: inline, like spans and anchors.

The Firefox bug report was filed way back in the days of Firefox 1 nine years ago. Yes, you read that right. It sat there, unfixed, while every other browser in the world implemented it.

Anyway, today web developers everywhere can rejoice. Now, at last, the released version of every major browser supports display: inline block. So, with only another year or two waiting while FF2 users upgrade to FF3, designers will be able to start using this singularly useful CSS rule (at least in cases where IE supports it as well).

A parting example

A parting example of the kind of cool trick you can play with inline-block: text flowing inside a sized box that is itself flowing inside text.

Code for flowing text inside flowing text:


<div style="font-size: 250%; width: 600px;">
  Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor 
    <span style="width: 130px; height: 40px; font-size: 9px; display: inline-block;
      padding: 1em; border: 1px solid black; overflow: hidden;">
      Duis aute irure dolor in reprehenderit in voluptate velit esse cillum 
      dolore eu fugiat nulla pariatur.
    </span>  
  incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam.   
  </div>

How it renders in a compliant browser … including IE6!*

Tricks with flowing text

*Well, more or less. IE6 gets it reasonably close.