Never been to DZone Snippets before?

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

About this user

Arjan van der Gaag http://agwebdesign.nl

« Newer Snippets
Older Snippets »
Showing 1-1 of 1 total  RSS 

Helpful extensions to core Ruby classes

If you find yourself doing this a lot:

   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.
« Newer Snippets
Older Snippets »
Showing 1-1 of 1 total  RSS