Syntactical Sugar

| Comments

On recent rails projects, I found myself clinging to a few useful helpers and additions. Here’s a few.

hide_unless

Often in views, I find I want to hide a particular div or element, but only if certain conditions are met. An ajax call might later reveal it, or replace the contents of the div with something.

1
2
3
 def hide_unless(condition)
    condition ? '' : 'display:none'
 end

In use:

1
<div id="edit_pane" style="<%= hide_unless(@story) %>"></div>

present?

Rails gives us .blank?, but I hate writing things like:

1
2
3
  <% if !@stories.blank? %>
    ... etc
  <% end %>

So, I add this as an extension in my projects:

1
2
3
4
5
class Object
  def present?
    !blank?
  end
end

And obviously it works on anything: arrays, hashes, nil, etc.

1
2
3
<% if session[:setting].present? %>
   etc...
  <% end %>

UPDATE (29-Jun-2008): DHH just committed this to Edge Rails. I am certain that I had nothing to do with it, but I’ll pretend :)

user_owns_it

A common task is to check if the current user owns a particular resource.

1
2
3
  def user_owns_it(asset)
    asset.respond_to?(:created_by) and asset.created_by and current_user and asset.created_by.id == current_user.id
  end

This allows easy checking in views:

1
2
3
<% if user_owns_it(@post) %>
   link_to "Edit Your Post", edit_post_path(@post)
<% end %>

Please share if you have other interesting tidbits from your toolbox!

Comments