ScratchyPad Tag Clouds

The version I posted yesterday had a dodgy tag cloud implementation that I was experimenting with. I’ve reworked it this morning between other tasks and am much happier now. I imported some delicious bookmarks to populate the db a bit more and the result is this:

Much better!


Initially, the tag cloud was overpowered by one tag because I was using a linear weighting, but once I switched to using a logarithmic weighting, things looked a lot better.

This is how the tag cloud is rendered, using Markaby:

  1. # Render the tag cloud view
  2. def tag_cloud(tags = nil)
  3.   @tags ||= tags
  4.   max = 0
  5.   @tags.each do |t|
  6.     max = t.taggings.length if t.taggings.length > max
  7.   end
  8.  
  9.   div.cloud do
  10.     @tags.each do |t|
  11.       weight = Math.log10(t.taggings.length) / Math.log10(max.to_f)
  12.       _cloud_tag(t, weight)
  13.     end
  14.   end
  15. end
  16.  
  17. # Generate tag HTML
  18. def _tag(name, style = nil)
  19.   a.tag(name, :href => R(Tags, name), :title => "All entries tagged ‘#{name}’", :style => style)
  20. end
  21.  
  22. # Generate the HTML for the tag in the cloud
  23. def _cloud_tag(tag,weight)
  24.   _tag(tag.name,style_for_weight(weight))
  25.   self << " "
  26. end
  27.  
  28. # Generate a CSS style string
  29. def style_for_weight(weight)
  30.   n = 0xff/2 + (0xff/2*weight).to_i
  31.   "font-size:#{0.5 + weight}em;color:rgb(#{n},#{n},#{n})"
  32. end

Leave a Reply