Skip to content

Instantly share code, notes, and snippets.

@zealot128
Created December 16, 2011 21:21
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 zealot128/1488047 to your computer and use it in GitHub Desktop.
Save zealot128/1488047 to your computer and use it in GitHub Desktop.
Ruby - HTML Tagcloud with easy changeable formular

Tagcloud Calculation

Usage

Calculate weight of given array. e.g. %w[ruby ruby ruby rails]

Tagcloud.tagcloudize [ "rails", "ruby", "rails" ...] do |count,max|
 90 + 110 * ( count / max.to_f)
end

results in:

[{:text=>"rails", :count=>1, :size=>126}, {:text=>"ruby", :count=>3, :size=>200}]

Now, one can use some kind of helper to generate html (not included in this gist, to keep independence), or here directly in haml:

Tagcloud.tagcloudize(array).each do |e|
  %span{:style => "font-size: #{e[:size]}%"}
    = link_to e[:text], search_path(:q => e[:text])

just to make the point, Stuff like this should be put into a helper or partial.

Improvements:

  • Instead of direct size calculation, calculate levels for css classes. More prettier :)
# from ruby stats
class Array
def histogram ; self.sort.inject({}){|a,x|a[x]=a[x].to_i+1;a} ; end
end
# Usage:
# Tagcloud.tagcloudize [ "rails", "ruby", "rails" ...] do |count,max|
# 90 + 110 * ( count / max.to_f)
# end
# means: calculate tagcloud. Minsize 90, maxsize 90+110=200
#
#
# Expects [ "rails", "ruby", "rails" ...]
class Tagcloud
# Expects [ "rails", "ruby", "rails" ...]
def self.tagcloudize(array)
return [] if array.blank?
distribution = array.histogram
max = distribution.max_by{|a,b|b}[1]
distribution.map do |text,count|
if block_given?
size = yield(count,max)
else
size = Tagcloud.default_formula(count,max)
end
{:text => text, :count => count, :size => size.to_i}
end
end
def self.default_formula(count,max)
90 + 110 * ( count / max.to_f)
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment