Sinatra Helpers

Apr 25

Helpers in Sinatra are methods that can be called from within a handler and any views. They are useful for cutting down on any repetitive tasks that you might want to do. Creating helpers in Sinatra is really easy, all you do is place them inside the helpers block, like so:

helpers do
  #helper methods go here

To illustrate this, I’m going to create an example of a link_to helper, like the one found in Rails.

helpers do

def link_to(url,text=url,opts={})
  attributes = ""
  opts.each { |key,value| attributes << key.to_s << "=\"" << value << "\" "}
  "<a href=\"#{url}\" #{attributes}>#{text}</a>"


This helper takes 2 arguments. The first argument is the url that you want to link to. The second is the text that you want displayed, which defaults to the url if you don’t put any in. You can also add additional options as a hash to add extra attributes to the <a> tag that is created. Here are a few examples that would be used in the views (using erb):

<%= link_to '' %>
=> <a href=""></a>

<%= link_to '','Sinatra Website' %>
=> <a href="">Sinatra Website</a>

<%= link_to '','Sinatra Website', {:class=>'link',:id=>'sinatra'} %>
=> <a href="" class="link" id="sinatra">Sinatra Website</a>

I find this a very useful helper to use when developing and find it much more easier to read than straightforward html. It becomes more useful if you also have some url helper methods as well. The following example is quick to write and easy to read:

<%= link_to home_url,"Home" %>

Don’t forget that helpers can also be used in the handlers as well as views. For example, you might have a helper method called logged_in? that tests if a user has logged in or not. This could be used in a handler to display an admin page if they are logged in, or the normal home page if not:

get '/' do
  if logged_in?
    erb :admin_page
    erb :home_page

The same helper method could also be used in a view to display different messages depending on whether the user is logged in or not:

<% if logged_in? %>
  <p>You are logged in as <%= %></p>
<% else %>
  <p>You are not logged in.</p>
<% end %>

Anybody got any ideas about how the link_to helper could be improved? Any other useful helpers that people use?

blog comments powered by Disqus