The Daily Refactoring

for Friday, October 24, 2008


Last update: 12:02 PM EDT
HOME PAGE

Cleaning up Flash Messages in our Views

From Ruby Refactoring: Replacing a Loop with Closure Collection Method

By COREY GRUSDEN, SANDRO TURRIATE, and ZACH INGLIS
Published: 02:30 PM EDT

We had conditional code that was appearing in multiple views and getting rid of it was a high priority to us since duplicated code is known as a Code Smell and does more harm than good. So we decided to move the code into a Module and call the method from there.

  def render_flashes
    flashes = ""
    [:notice, :error].each do |type|
      unless flash[type].nil?
        flashes += content_tag('div', flash[type], :id => "flash_#{type}", :class => type)
      end
    end
    flashes
  end

We then realized that we could use Replacing a Loop with Closure Collection Method to get rid of the local variables as well as utilize the power of Ruby’s enumeration closures.

  1. The .collect method will build an array from what’s returned from the block instead of concatenating a string from content_tag
  2. Removing the flash[type].nil? is possible since enumerating values in the hash will not return anything if values are nil
  3. When the code is output to the view, it will be nicely formatted underneath since we can call .join on the array that is created from .collect
  def render_flashes
    flash.collect do |key, message|
      content_tag :div, message, :id => "flash_#{key}", :class => key
    end.join('\n')
  end