Never been to DZone Snippets before?

Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

About this user

Arjan van der Gaag http://agwebdesign.nl

« Newer Snippets
Older Snippets »
Showing 1-1 of 1 total  RSS 

Helpers for placeholder messages

When there are no results to display for a user you often want to tell so using a placeholder message, such as 'Sorry, no posts matched your criteria' or 'You have no recent purchases'.

I created these two helpers to make using placeholder a little bit easier.

   1  
   2  def placeholder(message = 'Nothing to display', options = {}, &proc)
   3    # set default options
   4    o = { :class => 'placeholder', :tag => 'p' }.merge(options)
   5  
   6    # wrap the results of the supplied block, or
   7    # just print out the message
   8    if proc
   9      t = o.delete(:tag)
  10      concat tag(t, o, true), proc.binding
  11      yield
  12      concat "</#{t}>", proc.binding
  13    else
  14      content_tag o.delete(:tag), message, o
  15    end
  16  end
  17    
  18  def placeholder_unless(condition, *args, &proc)
  19    condition ? proc.call : concat(placeholder(args), proc.binding)
  20  end


Now you can use it as follows:

   1  
   2  <%= placeholder :message => 'Nothing found' %>
   3  
   4  <% placeholder do %>
   5  Nothing found.
   6  <% end %>


Results in:

   1  
   2  <p class="placeholder">Nothing found</p>


The second function allows the following usage:

   1  
   2  <% placeholder_unless @posts.any?, 'No posts found' do %>
   3    <%= render :partial => @post %>
   4  <% end %>


The point is it all results in a nice, painless message with consistent markup and styling and I find it makes my code a bit more readable.

I'm sure the code could be optimized but for now it works.
« Newer Snippets
Older Snippets »
Showing 1-1 of 1 total  RSS