17 June 2011

Display Avatar in Ruby on Rails application

Now a days displaying Avatar is a common trend in web technology. Avatar is graphical representation of an user. Thanks go to Tom Preston Werner for introducing Gravatar , a great web service which give globally recognized avatar. You just need to open up an account out their with an email address and upload your photo. Different websites, consuming Gravatar's service can display your photo if you register out there with the same email address.

In this example I will show you a way to display Gravatar in your Ruby on Rails web application.

First I will write a helper method which will return an image url for displaying Avatar. Gravater, id is simply the MD5 hexdigest of the email address. So the line returning avatar id will be:
gravatar_id = Digest::MD5.hexdigest(user.email.downcase)

I would like to display the avatar as 48x48, which is the usual size of a twitter display image. Also, I want to show a default image url if avatar is not shown. For these two, we need to pass some extra parameters. The method will look like:

def avatar_url(user)
    default_url = "#{root_url}images/default-image.jpg"
    if(user.present?)
        gravatar_id = Digest::MD5.hexdigest(user.email.downcase)
        return "http://gravatar.com/avatar/#{gravatar_id}.png?s=48&d=#{CGI.escape(default_url)}"
    else
      return default_url
 end
end
In your view:

<%= link_to(image_tag(avatar_url(user)), user_path(user.id))%>

The above line, will show the avatar and will take you to the show method of UsersController if you click on it.

You can also choose from an user to display his avatar from gravatar or your local file system. All you need to do is to have a boolean field 'avatar' in your User table and re-arrange the logic in avatar_url method.

It's that simple! Happy coding!!



05 March 2011

SEO friendly URL in ruby on rails and friendly_id



By default Rails generate URL with ID. In short to_param method returns a string, which Action Pack uses for constructing an URL to this object. The default implementation returns records’ id as a string.
Suppose, we have a Category model. The routes.rb will look like:
map.resources :categories
In categories.rb controller:
@category = Category.find(1)
In view index.html.erb:
<%=link_to(@category.title,category_path(@category))%>
This will generate the URL: /category/1

While working on building a website Khan Academy In Bangla as a part of the translation project of Khan Academy , I realized that a SEO friendly URL is mandatory. In this website, I have categories like physics, biology or math and tutorials under each category. In order to make the user friendly URL I needed to overwrite to_param method in model.

In order to make it SEO friendly, in Category.rb model I added the line:
def to_param
  "#{id}-#{title.downcase.gsub(/[^a-zA-Z0-9]+/, '-').gsub(/-{2,}/, '-').gsub(/^-|-$/, '')}"
end
The regular expression will remove any special character. It generates the url: /category/1-biology. Looks better, right?
Although the URL has become SEO friendly now but this method has some drawbacks. To summarize some:

1. It appends the id with the name. If we remove ID, then maintaining uniqueness will be a problem
2. If the title field is edited then the URL will be changed causing SEO to break.
3. For a large application, it will not be feasible to overwrite to_param in tons of model.

In this point, I found a nice plugin/gem to make all these pretty simple and it is friedly_id . It will do all the work for you with some simple steps. For my system what I did were:
1. Install the gem:
gem install friendly_id
2. In environment.rb include the gem.
require 'friendly_id'
3. Generate friendly_id by going to my application directory:
cd khanacademybangla
script/generate friendly_id
4. Run the migration
rake db:migrate
5. Add has_friendly_id to the models which I am looking for to generate user friendly id
class Category < ActiveRecord::Base
has_friendly_id :title, :use_slug => true
end
6. Run a rake task to generate slugs for existing records:
rake friendly_id:make_slugs MODEL=ModelName
For my example it was:
rake friendly_id:make_slugs MODEL=category
That’s it! Now we will be able to see a completely SEO friendly url: /category/biology

I am yet to push my code to production! You need to wait till tomorrow to see it live.

13 January 2010

Displaying status feed of twitter in Rails

Couple of days ago I needed to show twitter status in a rails application. The specification was to show the last 5 status of a twitter account. Twitter itself has a good API. But I used twitter gem which left me to do just a couple of lines of code.

Twitter gem supports both OAuth and HTTP Auth. I used HTTP Auth for authentication. Let me dig in to code.

First of all, install twitter gem.

gem install twitter
Load ruby gem to environment.rb.
require 'twitter'

Then perform the authentication using HTTP Auth. You need to provide your user id and password of the twitter account. You should read this from a config file. For the simplicity I am placing it at code.

def twitter_feed   
httpauth = Twitter::HTTPAuth.new(‘twitter_account_name’, ‘twitter_account_password’)    
twitter_client = Twitter::Base.new(httpauth)
@latest_status_feeds = twitter_client.user_timeline[0..4] if twitter_client.present?
#it will show most recent 5 status. If you would like to show recent 20 don't put any bar.
render :partial=>"twitter_feed"   
end

In twitter_feed partial you can display the text using some properties.

<h4>Latest Tweet</h4>   
<%if @latest_status_feeds.present?%>    
  <%  @latest_status_feeds.each do | @latest_status_feed|%>    
    <p>"<%= @latest_status_feed.text %>"<br /><span class="time" style="font-size:11px;font-style:italic;">
<%= convert_date(@latest_status_feed.created_at.to_date) %></span></p>    
       
  <%end%>    
<%end%>

This will show the last 5 status from your twitter feed.

If you would like to show the twitter feeds of your friends, the following tweak is needed to be made:

    @friends_feeds =     twitter_client.friends_timeline 

You can display from the view in the same way!

That's it! Pretty simple, yeah? Happy coding.

31 December 2009

Presentation on bad smells in code

Most of you must have read the famous book on “Refactoring” written by Martin Fowler. Based on this book and and my fellow colleague Rashed Kibria presented at the BASIS, titled as “Bad Smells in code (Part-1)”. We have shared the document. You can take a look at it.

Bad Smell in Codes-1

30 December 2009

Formatting date in Rails

The thing with which we deal everyday in our programming life is “Date”. This small, delicate stuff needs to be displayed in different formats in different places! In Rails there are many useful helpers to format date. Hence I am jolting down some so that I can take look quickly if I need one of them to use. You can take a look at it, too.

I have used strftime function of ActiveSupport class.

current_time = Time.now #today is 30 December, 2009
current_time.strftime("%m-%d-%y") # "12-30-09"
current_time.strftime("%b %d, %Y %I:%M%p") # "Dec 30, 2009 10:23PM"
current_time.strftime("%A %d, %B %Y") # "Wednesday 30, December 2009"
current_time.strftime("%A, %d %B %Y %I:%M%p") # "Wednesday, 30 December 2009 10:33PM"
current_time.strftime("%Y-%m-%d %H:%M:%S") # "2009-12-30 22:33:55"
current_time.strftime("%b %d, %Y") #=> "Dec 30, 2009"


By this time you may have understood the meaning of this format. Here is the explanation:

%Y – 2009 – Year with century

%y – 09 – Year without century

%B – January – Full month name

%b – Jan – Short month name

%m – 12 – Month number

%A- Wednesday-Full weekday name

%a- Wed-Short weekday name

%H –22 – Hour

%M –33 – Minute

%S –55 - Second

%p – AM or PM