Over a million developers have joined DZone.

Helpful Extensions To Core Ruby Classes

·
If you find yourself doing this a lot:


<% if @collection.any? -%>
    <% for item in @collection %>
  1. <%= item %>
  2. <% end -%>
<% 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
  • #{item}
  • \n" } << "\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("
    \n") { |o, p| o << "\t
    #{p[0]}
    \n\t
    #{p[1]}
    \n" } << "
    \n" if self.any? end
    Extending core classes is a bit dangerous but I use these in almost every Rails project.
    Topics:

    {{ parent.title || parent.header.title}}

    {{ parent.tldr }}

    {{ parent.urlSource.name }}