Skip to content

Instantly share code, notes, and snippets.

@trobrock
Created May 31, 2010 20:07
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save trobrock/420215 to your computer and use it in GitHub Desktop.
Save trobrock/420215 to your computer and use it in GitHub Desktop.
A helper for rails to create a tag cloud out a string of words (space delimited). Adapted the idea from here: http://snippets.dzone.com/posts/show/6027
def word_cloud(words)
wordcount = {}
words.split(/\s/).each do |word|
word.downcase!
if word.strip.size > 0
wordcount[word.strip] = (wordcount.key?(word.strip)) ? (wordcount[word.strip] + 1) : 0
end
end
s = []
wordcount.each_value do |v|
s << v
end
s = s.sort.reverse.slice(0,20)
min, max = s.last, s.first
ratio = 18.0 / (max - min)
cloud = String.new
wordcount.each_key do |word|
font_size = (9 + (wordcount[word] * ratio))
cloud += link_to word, search_path(:type => "tag", :term => word), :style => "font-size: #{font_size}pt;"
cloud << " "
end
cloud
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment