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

Tag Cloud - Ruby Class

09.05.2008
| 5658 views |
  • submit to reddit
        Create a Tag Cloud in Ruby. It's a port of a PHP Class I used to use.
It works.

# TagCloud
#
# Create a Tag Cloud from a string of words
# - fernyb
#
#   cloud = TagCloud.new("a very long string with many word")
#   cloud.klass = "css-Class"
#   puts cloud.build 
#
class TagCloud
  attr_accessor :klass
  
  def initialize(words)
    @wordcount = count_words(words)
  end
  
  def count_words(words)
    wordcount = {}
    words.split(/\s/).each do |word| 
      word.downcase!
      if word.strip.size > 0
        unless wordcount.key?(word.strip)
          wordcount[word.strip] = 0
        else
          wordcount[word.strip] = wordcount[word.strip] + 1
        end
      end
    end
    wordcount
  end
  
  def font_ratio(wordcount={})
    min, max = 1000000, -1000000
    wordcount.each_key do |word|
      max = wordcount[word] if wordcount[word] > max
      min = wordcount[word] if wordcount[word] < min
    end
    18.0 / (max - min)
  end
  
  def build
    cloud = String.new
    ratio = font_ratio(@wordcount)
    @wordcount.each_key do |word|
      font_size = (9 + (@wordcount[word] * ratio))
      cloud << %Q{<span#{" class=\"" + klass + "_span\"" unless klass.nil? }><a href="#"#{" class=\"" + klass + "\"" unless klass.nil? } style="font-size:#{font_size}pt;">#{word}</a></span> }
    end
    cloud
  end
end