DZone Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

Snippets has posted 5883 posts at DZone. View Full User Profile

Helpful Extensions To Core Ruby Classes

  • submit to reddit
        If you find yourself doing this a lot:

<% if @collection.any? -%>
  <% for item in @collection %>
    <li><%= item %></li>
  <% end -%>
<% end -%> 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?

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?

Extending core classes is a bit dangerous but I use these in almost every Rails project.