Showing posts with label ruby on rails. Show all posts
Showing posts with label ruby on rails. Show all posts

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!!



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

29 December 2009

Some useful number helpers in rails

In my previous blog on Rails I discussed about some useful text helpers for rails based on my work experience on Scrumpad. Now I would like to shade on some useful number helpers in rails which made my life easy during the project work. Let’s dive into some samples!


1. number_to_currency
Software developers do the complex thing and forget about small ones. Sometimes after design discussions, writing a lot of lines of codes with complex logic create a number. Say, bill of a particular company for the month of January! When you will deliver the result to your product owner with pride, he will take a look at the number (you are expecting a pat on your back ) and ignoring your days of work may start talking with an unsatisfied face that “You forgot the currency. Is it in pound? I will be damn rich, then”. Now you come down to the earth! What a silly thing it was using number helpers in rails!! These methods are from ActionView::Helpers::NumberHelper
number_to_currency(1234.506)  # $1234.51
number_to_currency(1234.506, :precision=>3)  # $1234.506
number_to_currency(1234.506, :precision=>3, :unit=>”&pound”)  # &pound1234.506

2. number_to_human_size
A lot of systems deal with user interaction now a days. Attachment is an important part of it. Users like to upload files like images, texts, documents and so on. Beside a beautiful icon of that attachment, it is nice to mention the size of that file. It can be easily done by rails using this function.

number_to_human_size(123) # 123 Bytes
number_to_human_size(1234) # 123 KB
number_to_human_size(1234567) # 1.2 MB

It can be used with precision and separator, too.

number_to_human_size(1234567, :precision=>2, :separator=>’,’) # 1,18 MB

3. number_to_percentage
It formats a number as percentage strings.  At some places discount is calculated dynamically based on number of active users. Here comes a useful helper.

number_to_percentage(100) #100%

4. number_to_phone
It formats a phone number to US phone number format. Once can customize it, too. It takes area code, country code, extension as option hash.

Let’s give some example:

number_to_phone(1115678) # 111-5678
number_to_phone(1114567890, :area_code=>true) # (111) 456-7890
number_to_phone(1114567890, :area_code=>true, :extension=>999) # (111) 456-7890 x 999
number_to_phone(1114567890, :country_code=>1 # +1- 111 - 456-7890

So, based upon your requirement you can show the user phone number.

That’s it for today. I will come shortly with more helper that I usually use! Happy coding :-)

19 August 2009

Showing success/failure message for CRUD in rails

How do you know whether a CRUD is successful in rails?How do you show an user friendly error message based on different error? Here is a brief description:


#create

def create
@is_success = false
@build = Build.new(params[:build])
begin
@build.save!
@is_success = true
rescue Exception=>ex
@message = "Build cannot be saved because #{ex.message} "
end
end


Now from view based on the value of @is_success you can deliver user friendly message. What in case of update? The code will look somehow different. :-)

def update
@build = Build.find(params[:id])
@is_success = @build.update_attributes!(params[:build])
end


Now comes destroy!
If the destroy() is succesful then frozen method will return true! That is how you can be sure whether an object is deleted!


def destroy
@is_success = false
@build = Build.find(params[:id])
@build.destroy()
@is_success = @build.frozen?
end

That's it! Simple!! Happy coding :-)

10 January 2009

Setting user defined time zone in Rails 2.1

Time zone support in rails is now easier than ever. You can set your time zone dynamically based on users information.

Here are the steps:


In configuration file, config/environment.rb add the following line
config.time_zone = "UTC"

You can prompt from user for their time zone and save it in the database for future reference. For the population of time zones in the dropdown list add the following line in you *.rhtml file:

<%= time_zone_select "user", "time_zone", TimeZone.all%>

Save this data in the database field.
When the user will be logged in fetch the time_zone from database and set it at Time.zone.
def set_timezone(time_zone)
Time.zone = time_zone
end

To persist it every where make sure to call it:
set_timezone(@logged_in_user.time_zone)

That’s it!

03 December 2008

Redirecting a http request to https in Rails

In my previous blog i instructed how to install a SSL certificate in server. In this tutorial I will provide you some insights on how to redirect a http request to a https.

we need two methods:


1. One is for going to from http to https:
def require_https  
redirect_to :protocol => "https://" unless (request.ssl? or local_request? or request.post? or ENV["RAILS_ENV"]=="development")   
end

2. The other is the reverse of this one, that is going from https to http:

def require_http  
redirect_to :protocol => "http://" if (request.ssl?)   
end


Now you can call these two function where it is necessary like:
before_filter :require_https


In this point you may get an error like “Infinite Redirection loop”. In order to solve this problem add the following line at
RequestHeader set X_FORWARDED_PROTO 'https'

So the config file should be something like this:


RequestHeader set X_FORWARDED_PROTO 'https'  
SSLEngine on    
SSLCertificateFile /etc/apache2/SSL_Files/abc.crt    
SSLCertificateKeyFile /etc/apache2/SSL_Files/abc.key    
SSLCertificateChainFile /etc/apache2/SSL_Files/gd_bundle.crt    

Now any request coming to http should be redirected to https.

Hope this will serve your purpose. Happy coding!!