In you rails application if you are using acts_as_taggable plugin for creating tags you often need to use tag cloud. To create a tag cloud using acts_as_taggable plugin its simple. We need to add some code in tagaable plugin.
It is as follows:
Add a new method in the Tag model provided by the acts_as_taggable plugin. Open the vendor/plugins/acts_as_taggable/lib/tag.rb file and add the following method:
def self.tags(options = {})
query = "select tags.id, name, count(*) as count"
query << " from taggings, tags"
query << " where tags.id = tag_id"
query << " group by tag_id"
query << " order by #{options[:order]}" if options[:order] != nil
query << " limit #{options[:limit]}" if options[:limit] != nil
tags = Tag.find_by_sql(query)
end
This method will return the id, name, and usage count for each tag. This method also provides a way to limit and order the tags. Once we have added the new method in the Tag model we will need to add a method to the application helper which will help in selecting the right style class for each tag. Add the following function to app/helpers/application_helper.rb:
def tag_cloud(tags, classes)
max, min = 0, 0
tags.each { |t|
max = t.count.to_i if t.count.to_i > max
min = t.count.to_i if t.count.to_i < min
}
divisor = ((max - min) / classes.size) + 1
tags.each { |t|
yield t.name, classes[(t.count.to_i - min) / divisor]
}
end
Now focus on the controller and view. In the controller you can use the following bit of code to get the the first one hundred tags order by name:
@tags = Tag.tags(:limit => 100, :order => "name desc")
In the view we will use the tag_cloud method so that it will select the right css class based on the tag usage count. Here is the view code:
<% tag_cloud @tags, %w(nube1 nube2 nube3 nube4 nube5) do |name, css_class| %>
<%= link_to name, {:action => :tag, :id => name},
:class => css_class %>
<% end %>
In the Css file add the following line.
.nube1,.nube1:hover, .nube1:active, .nube1:visited {text-decoration:underline;font-size: 1.2em;font-weight: 100;margin-left:1px;color:#000000;}
.nube2,.nube2:hover, .nube2:active, .nube2:visited {text-decoration:underline;font-size: 1.4em;font-weight: 300;margin-left:1px;color:#000000;}
.nube3,.nube3:hover, .nube3:active, .nube3:visited {text-decoration:underline;font-size: 1.6em;font-weight: 500;margin-left:1px;color:#000000;}
.nube4,.nube4:hover, .nube4:active, .nube4:visited {text-decoration:underline;font-size: 1.9em;font-weight: 700;margin-left:1px;color:#000000;}
.nube5,.nube5:hover, .nube5:active, .nube5:visited {text-decoration:underline;font-size: 2.2em;font-weight: 900;margin-left:1px;color:#000000;}
.nube6,.nube6:hover, .nube6:active, .nube6:visited {text-decoration:underline;font-size: 2.5em;font-weight: 1100;margin-left:1px;color:#000000;}
0 comments:
Post a Comment