Created
May 31, 2010 20:07
-
-
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
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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