Helpful extensions to core Ruby classes
1 2 <% if @collection.any? -%> 3 <ol> 4 <% for item in @collection %> 5 <li><%= item %></li> 6 <% end -%> 7 </ol> 8 <% end -%>
...you might want to extend two Ruby core classes to automagically print out HTML-lists. Extend Array with:
1 2 def to_html_list(type = :ol) 3 self.inject("<#{type}>\n") { |output, item| output << "\t<li>#{item}</li>\n" } << "</#{type}>\n" if self.any? 4 end
Now you can produce both OL (default) and UL lists. You can easily convert a Hash into a DL-list by extending it like so:
1 2 def to_html_list 3 self.inject("<dl>\n") { |o, p| o << "\t<dt>#{p[0]}</dt>\n\t<dd>#{p[1]}</dd>\n" } << "</dl>\n" if self.any? 4 end
Extending core classes is a bit dangerous but I use these in almost every Rails project.