Ruby snippet: Return a different string if empty or if replacing

December 24, 2008 – 12:53 am

In my latest Rails project I needed a quick way to return a string if that string happened to be blank, and also a way to return a different string if the existing string is set. Here’s the solution I came up with which I placed in extras.rb in my lib directory (require ‘extras’ in environment):

def otherwise(alternate, existing = nil)
    self == existing ? alternate : self
end

I’m using it like so in my project:

<!-- If it's blank -->
<%= image_tag(image.general_filename('large'), :class => "full", :alt => (h image.description.otherwise(image.project.title))) %>

<!-- If it has a string you would like to replace -->
<%= image_tag(image.general_filename('large'), :class => "full", :alt => (h image.description.otherwise(image.project.title, "No description"))) %>

Post a Comment