Helpful extensions to core Ruby classes
<% if @collection.any? -%> <ol> <% for item in @collection %> <li><%= item %></li> <% end -%> </ol> <% end -%>
...you might want to extend two Ruby core classes to automagically print out HTML-lists. Extend Array with:
def to_html_list(type = :ol) self.inject("<#{type}>\n") { |output, item| output << "\t<li>#{item}</li>\n" } << "</#{type}>\n" if self.any? 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:
def to_html_list self.inject("<dl>\n") { |o, p| o << "\t<dt>#{p[0]}</dt>\n\t<dd>#{p[1]}</dd>\n" } << "</dl>\n" if self.any? end
Extending core classes is a bit dangerous but I use these in almost every Rails project.