Tim Riley

A Cycle Helper for Sinatra

February 13th 2009

Sinatra’s minimalist tack encourages you to build just the number of helpers that is required for your app. In doing so, it’s also a chance to improve your Ruby fu. While the source for the helpers that come with Rails provides an excellent starting point for your particular subset, they’re often built to keep all comers happy. You can do something a lot slimmer for your narrowly focused Sinatra app.

Bicycle

Here’s what I came up with for a cycle helper to alternately colour table rows via cycling their CSS classes:

Update: check the end of this post for some improved solutions!

helpers do
  def cycle
    @_cycle ||= reset_cycle
    @_cycle = [@_cycle.pop] + @_cycle
    @_cycle.first
  end

  def reset_cycle
    @_cycle = %w(even odd)
  end
end

For reference, this is the source for Rails' equivalent set of helpers, comprising about one hundred or so lines of code. Now, here are my helpers in use:

%table.tickets{:cellpadding => 0, :cellspacing => 0}
  %thead
    %tr
      %th No.
      %th Summary
      %th Reporter
      %th Assignee
      %th Updated
  %tbody
    - reset_cycle
    - group.tickets.each do |ticket|
      %tr{:class => "#{ticket.out_of_bounds? ? 'out-of-bounds' : 'unassigned'} #{cycle}"}
        = partial('ticket_row', :locals => {:ticket => ticket})

Nothing like writing your own helpers for a nice sense of achievement! And now a question for you? Can you think of a neater way to cycle through a series of strings? Would love to hear your feedback.

Update: Oceanic Ruby guru Lachie Cox has forked my helpers and provided some smarter versions. Thanks Lachie!

helpers do
  def cycle
    %w{even odd}[@_cycle = ((@_cycle || -1) + 1) % 2]
  end

  CYCLE = %w{even odd}
  def cycle_fully_sick
    CYCLE[@_cycle = ((@_cycle || -1) + 1) % 2]
  end
end
Tim Riley

Hi, I'm Tim Riley. I'm a web developer based in Canberra, Australia, where I work at a small design studio called Icelab. This is my blog, where I can share with you the things I learn as I go about building products for the web.

What I Build

Recent Presentations

  1. Facebook Authentication with OAuth
  2. JavaScript Testing with Capybara and Cucumber
  3. Using Titanium to Build Mobile Apps with JavaScript (audio)
  4. An Introduction to Sinatra
  5. Building your Capistrano Recipe Book