Tag Cloud in Ruby


/ Published in: Other
Save to your folder(s)



Copy this code and paste it in your HTML
  1.  
  2. def font_size_for_tag_cloud( total, lowest, highest, options={} )
  3. return nil if total.nil? or highest.nil? or lowest.nil?
  4. #
  5. # options
  6. maxf = options.delete( :max_font_size ) || 14
  7. minf = options.delete( :min_font_size ) || 11
  8. maxc = options.delete( :max_color ) || [ 0, 0, 0 ]
  9. minc = options.delete( :min_color ) || [ 156, 156, 156 ]
  10. hide_sizes = options.delete( :hide_sizes )
  11. hide_colours = options.delete( :hide_colours )
  12. #
  13. # function to work out rgb values
  14. def rgb_color( a, b, i, x)
  15. return nil if i <= 1 or x <= 1
  16. if a > b
  17. a-(Math.log(i)*(a-b)/Math.log(x)).floor
  18. else
  19. (Math.log(i)*(b-a)/Math.log(x)+a).floor
  20. end
  21. end
  22. #
  23. # work out colours
  24. c = []
  25. (0..2).each { |i| c << rgb_color( minc[i], maxc[i], total, highest ) || nil }
  26. colors = c.compact.empty? ? minc.join(',') : c.join(',')
  27. #
  28. # work out the font size
  29. spread = highest.to_f - lowest.to_f
  30. spread = 1.to_f if spread <= 0
  31. fontspread = maxf.to_f - minf.to_f
  32. fontstep = spread / fontspread
  33. size = ( minf + ( total.to_f / fontstep ) ).to_i
  34. size = maxf if size > maxf
  35. #
  36. # display the results
  37. size_txt = "font-size:#{ size.to_s }px;" unless hide_sizes
  38. color_txt = "color:rgb(#{ colors });" unless hide_colours
  39. return [ size_txt, color_txt ].join
  40. end
  41.  

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.