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.
def render_flashes flash.collect do |key, message| content_tag :div, message, :id => "flash_#{key}", :class => key end.join('\n') end