A Cycle Helper for Sinatra

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.

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

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

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

  def reset_cycle
    @_cycle = %w(even odd)

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}
      %th No.
      %th Summary
      %th Reporter
      %th Assignee
      %th Updated
    - 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.

Uppublished_at: 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]

  CYCLE = %w{even odd}
  def cycle_fully_sick
    CYCLE[@_cycle = ((@_cycle || -1) + 1) % 2]
© 2008-2018 Tim Riley. All rights reserved.