Friday, March 21, 2008

Tag clouds in Ruby and Rails


I love tags, it's a better way to classify content, and it's trendy, at least it was back in 2005. Tagcloud also gives you good visual indication of hot topics of the site content. I will share the method I use for creating a tagcloud in my sites. The trick of tagcloud is collecting all the tags for certain model and give each tag a weight in a scale from 1 to 5 for example. and then render a tagcloud which is basically tags rendered according to their weight, the most frequent tag is much bolder than the less frequent ones.



Tags models
Before using tags we need to create them first. I use a polymorphic relationship to tag several content types using two additional tables. The first table is the "tags" table which basically list all the tags used in the site, it is composed of a simple tag_id and name fields. The other table is the "taggings" tables. It holds all the relation ships between the content and the tags. It is actually a regular many to many association table but serve more than one content type. It may be easier to explain it in code.


class Book < ActiveRecord::Base
has_many :taggings, :as => 'taggable'
end

class Link < ActiveRecord::Base
has_many :taggings, :as => 'taggable'
end

class Tag < ActiveRecord::Base
has_many :taggings
end

class Tagging < ActiveRecord::Base
belongs_to :tag
belongs_to :taggable, :polymorphic => true
end


In these ActiveRecord models, Link and Book are content models which have many taggings, and each Tagging by its turn belongs to one tag. But notice in the has_many association in the Book and Link model that it we passed an "as => 'taggable'" that tell the ActiveRecord that Tagging belongs to a polymorphic model that is called 'taggable'. Taggable could be any model in your application and this pattern make your tagging mechanism support new models as you make them transparently, all you need to do is adding 'has_many as' association.

class Photo < ActiveRecord::Base
has_many :taggings, :as => 'taggable'
end


Create the database tables
The following is a basic Mysql schema for the tags, taggings tables:


CREATE
TABLE `tags` (
`id` int(10) unsigned NOT NULL auto_increment,
`name` varchar(255),
`created_at` datetime,
`updated_at` datetime,
PRIMARY KEY (`id`)
);

CREATE TABLE `taggings` (
`id` int(10) unsigned NOT NULL auto_increment,
`tag_id` int(11),
`taggable_type` varchar(20),
`taggable_id` int(11),
`created_at` datetime,
PRIMARY KEY (`id`)
);



Collecting the tags
The following is a method that could be located in a model probably taggings or in a helper.


def tags_cloud(model, limit=30)
options = {
:select => "count(taggings.id) as count_all, tags.name as tag_name, tag_id",
:conditions => {:taggable_type => model.to_s },
:joins => " left outer join tags on tags.id=taggings.tag_id" ,
:group => 'tag_id',
:order => 'count_all desc',
:limit => limit
}

sql = Tagging.send(:construct_finder_sql, options)

taggings = ActiveRecord::Base.connection.select_all(sql)

return [] if taggings.blank?

maxlog = Math.log(taggings.first['count_all'])
minlog = Math.log(taggings.last['count_all'])
rangelog = maxlog - minlog;
rangelog = 1 if maxlog==minlog
min_font = 1
max_font = 5
font_range = max_font - min_font
cloud = []
taggings = taggings.sort{|a,b| a['tag_name'] <=> b['tag_name']}

taggings.each do |tagging|
font_size = min_font + font_range * (Math.log(tagging['count_all']) - minlog)/rangelog
cloud << [tagging['tag_name'], tagging['tag_id'], font_size.to_i, tagging['count_all']] end
return cloud
end


If I use active record to find the required taggings it will then return a bunch of instantiated Tagging object and that would be a waste of memory and resources. It's better to make Active Record to only construct the SQL for us and then use the SQL to query the database directly.

I used an array with all regular select, conditions, joins and other arguments we usually use with the find method, and then use construct_finder_sql which is a private method of ActiveRecord, that's why i use send method to call it. And it returns the sql statement that i will use directly in an sql connection derived from the ActiveRecord::Base class.

I learned a trick from one of web2.0 books from Oreilly, I don't remember it right now, the trick is to make a contrast between the most frequent tags and less frequent ones using logarithm. Anyway you can figure it our yourself, or just use it as it is :)

The View
This is a sample of a view template that render the tagcloud. IT could be used as a base for a more sophisticated tagcloud.


<% the_cloud = tags_cloud(model) %>
<% unless the_cloud.blank? %>
<div id="big_tags_cloud">
<% the_cloud.each do |tag,id,fsize,count| %>
<span class="t<%= fsize -%>">
<
a title="<%= count %>"
alt="<%= count -%>"
class="tag_<%= id %>"
href="/<%= model.to_s.downcase %>s/tag/<%= id -%>">
<%=
tag %>
<
a>
<
span>
<% end %>
<
div>
<% end %>



Styling the cloud


#big_tags_cloud {padding:5px; text-align:justify; }
#big_tags_cloud a {font-family:'Times New Roman'; line-height:1.7;border-bottom:1px solid #779944;}
#big_tags_cloud span.t1 a{ color:#779944;font-size:11pt;}
#big_tags_cloud span.t2 a{ color:#779944;font-size:12pt;}
#big_tags_cloud span.t3 a{ color:#779944;font-size:13pt;}
#big_tags_cloud span.t4 a{ color:#558800;font-size:14pt;font-weight:bold;}
#big_tags_cloud span.t5 a{ color:#669900;font-size:15pt; font-weight:bold;}


2 comments:

Mike Subelsky said...

This was really helpful to get me going on my own tag cloud code, so thanks! One thing to fix, I had to round off the result of the font size calculation:

font_size = (min_font + font_range * (Math.log(tag['count_all']) - minlog) / rangelog).round

kopiluwak nya said...

http://bantalsilikon01.blogspot.com/2014/12/a.html
http://jualsangkarpleci.blogspot.com/2014/12/a.html
http://kopiluwakliar01.blogspot.com/2014/12/a.html
http://vvty.in/uncategorized/marinir-seo/

http://marinirseo.blogspot.com/2014/12/a.html
http://marinir-seo.blogspot.com/2014/12/a.html
http://bumbu-pecel-malang.blogspot.com/2014/12/a.html
http://distro-seo.blogspot.com/2014/12/a.html
http://restoran-seo.blogspot.com/2014/12/a.html
http://bantalmalangmurah.blogspot.com/2014/12/a.html
http://distrobantal.blogspot.com/2014/12/a.html
http://kesethandukmalang.blogspot.com/2014/12/a.html

http://gurunyaitu.blogspot.com/2014/12/b.htmlhttp://kedirinyaindah.blogspot.com/2014/12/a.htmlhttp://bumbupecel617.blogspot.com/2014/12/w.htmlhttp://akaeoleh.blogspot.com/2014/12/v.htmlhttp://satudiasaja.blogspot.com/2014/12/u.htmlhttp://goodluckyaa.blogspot.com/2014/12/t.htmlhttp://songolas11.blogspot.com/2014/12/r.htmlhttp://yudistiramlg.blogspot.com/2014/12/q.htmlhttp://arjunapnh.blogspot.com/2014/12/p.htmlhttp://marinirseo987.blogspot.com/2014/12/o.htmlhttp://ayoikut1.blogspot.com/2014/12/n.htmlhttp://sempelblogger.blogspot.com/2014/12/m.htmlhttp://hondajass.blogspot.com/2014/12/k.htmlhttp://kesetnyakaki.blogspot.com/2014/12/j.htmlhttp://alwayssate.blogspot.com/2014/12/i.htmlhttp://bumbupecelmlg7.blogspot.com/2014/12/h.htmlhttp://bumbunyaseo.blogspot.com/2014/12/g.htmlhttp://bumbupecel100.blogspot.com/2014/12/f.htmlhttp://smartfren1.blogspot.com/2014/12/e.htmlhttp://bumbumalang1.blogspot.com/2014/12/d.htmlhttp://bumbupecelmalang7.blogspot.com/2014/12/c.htmlhttp://marinirseo7.blogspot.com/2014/12/b.htmlhttp://bloggermalang1.blogspot.com/2014/12/a.htmlhttp://asfrt111.blogspot.com/2015/01/a.htmlhttp://fgrt445.blogspot.com/2015/01/a.htmlhttp://grte231.blogspot.com/2015/01/a.htmlhttp://htyu412.blogspot.com/2015/01/asdgt.htmlhttp://fgr453.blogspot.com/2015/01/a.htmlhttp://asw145.blogspot.com/2015/01/a.htmlhttp://gtry145.blogspot.com/2015/01/a.htmlhttp://ase476.blogspot.com/2015/01/a.htmlhttp://10ouy.blogspot.com/2015/01/a.htmlhttp://s9yt.blogspot.com/2015/01/a.html,http://marinir-seo-konsultan-12a.blogspot.com/2014/10/aaa.htmlhttp://asdf-14.blogspot.com/2014/10/hhh.htmlhttp://vvtiin.blogspot.com/2014/10/iii.htmlhttp://marinir-seo-8.blogspot.com/2014/10/jjj.htmlhttp://bantaljkt1.blogspot.com/2014/10/sss.htmlhttp://dfes12.blogspot.com/2014/10/rrr.htmlhttp://seo-guru01.blogspot.com/2014/10/qqq.htmlhttp://jksbindo.blogspot.com/2014/10/ppp.htmlhttp://jkt-49.blogspot.com/2014/10/ooo.htmlhttp://seokonsultan1.blogspot.com/2014/10/nnn.htmlhttp://guru-seo-malang.blogspot.com/2014/10/mmm.htmlhttp://seo-aaa.blogspot.com/2014/10/lll.htmlhttp://seo-konsultasi-mudah.blogspot.com/2014/10/kkk.htmlhttp://bantal-silikon15.blogspot.com/2014/10/ggg.htmlhttp://agen-seo16.blogspot.com/2014/10/fff.htmlhttp://agen-seo17.blogspot.com/2014/10/eee_30.htmlhttp://agen-seo18.blogspot.com/2014/10/ddd.htmlhttp://agen-seo19.blogspot.com/2014/10/ccc.htmlhttp://agen-seo20.blogspot.com/2014/10/bbb.htmlhttp://bumbu-pecel01.blogspot.com/2014/10/xxx.htmlhttp://bantalasdf.blogspot.com/2014/12/seo-sem-seo.htmlhhttp://seo-malang-19.blogspot.com/2014/10/bbb.htmlhttp://agenseomalang18.blogspot.com/2014/10/ccc.htmlhttp://marinirseo17.blogspot.com/2014/10/ddd.htmlhttp://bumbupecel16.blogspot.com/2014/10/eee.htmlhttp://domainhosting15.blogspot.com/2014/10/fff.htmlhttp://bumbupecel15.blogspot.com/2014/10/ggg.htmlhttp://marinirseo14.blogspot.com/2014/10/hhh.htmlhttp://bantalsilikon12a.blogspot.com/2014/10/iii.htmlhttp://marinirseo12.blogspot.com/2014/10/jjj.htmlhttp://bumbu-pecel-hz.blogspot.com/2014/10/kkk.htmlhttp://marinir-seo-001.blogspot.com/2014/10/lll.htmlhttp://bantal-silikon-murah.blogspot.com/2014/10/mmm.htmlhttp://vvty-ine.blogspot.com/2014/10/nnn.htmlhttp://give-a-power.blogspot.com/2014/10/ooo.htmlhttp://bumbupecel-12.blogspot.com/2014/10/ppp.htmlhttp://marinir-seo-konsultan.blogspot.com/2014/10/qqq.htmlhttp://guru-seo-praktisi-123.blogspot.com/2014/10/rrr.htmlhttp://guru-seminar-online01.blogspot.com/2014/10/sss.htmlhttp://kopiluwakmalang11.blogspot.com/2014/10/ttt.html

Finite-State Machines, Part 1: Modeling with Haskell Data Types

Stateful programs often become complex beasts as they grow. Program state incohesively spread across a bunch of variables, spuriously guar...