Platinum Partner

Tag Cloud - Ruby Class

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{#{word} }
    end
    cloud
  end
end

{{ tag }}, {{tag}},

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

{{ parent.tldr }}

{{ parent.urlSource.name }}
{{ parent.authors[0].realName || parent.author}}

{{ parent.authors[0].tagline || parent.tagline }}

{{ parent.views }} ViewsClicks
Tweet

{{parent.nComments}}