Getting gravatar images with Ruby on Rails

What Is Gravatar?

An “avatar” is an image that represents you online—a little picture that appears next to your name when you interact with websites.A Gravatar is a Globally Recognized Avatar. You upload it and create your profile just once, and then when you participate in any Gravatar-enabled site, your Gravatar image will automatically follow you there.

Understanding how to get images from Gravatar

When you sign up in gravatar, you need to register an unique e-mail. Gravatar uses that email address to generate an unique MD5.hexdigest key, and then, it links that key to your image file.

Let’s take a look at my gravatar  image url:

http://gravatar.com/avatar/1c7b91342323ab699f6668f3317ed1bb

Parameter after the avatar is the MD5.hexdigest key generated with your email, let’s try generate that in our application and check if it gives the same result:


require "digest/md5"
Digest::MD5.hexdigest('meghagulati30@gmail.com').to_s

Result is “1c7b91342323ab699f6668f3317ed1bb”

So now you can write your own tool to get the gravatar user image: just use the email to generate the key and append it to the url.

If you are looking for more options while fetching the image you can use gems like gravtastic which lets you get images of different sizes, avatar rating and different filetype.

Advertisements

Sitemap.xml on Heroku with Ruby on Rails

Steps to generate dynamic sitemap.xml for Ruby on Rails site hosted on Heroku.

1) Remove /public/sitemap.xml if it exists.

2) Add following to routes.rb


resources :sitemaps, :only => :show
get "sitemap" => "sitemaps#show"

3) Create sitemaps controller


 rails g controller sitemaps

4) Update SitemapsController with following code


class SitemapsController 
  def show
    @posts = Post.where(:active => true) #we are generating url's for posts
    respond_to do |format|
     format.xml
    end
  end
end

5) Create /app/views/sitemap/index.xml.builder with the following content.


base_url = "http://#{request.host_with_port}"
xml.instruct! :xml, :version=>'1.0'
xml.tag! 'urlset', 'xmlns' => 'http://www.sitemaps.org/schemas/sitemap/0.9' do
  xml.url{
      xml.loc("http://example.com")
      xml.changefreq("weekly")
      xml.priority(1.0)
  }
  xml.url{
      xml.loc("http://example.com/posts")
      xml.changefreq("daily")
      xml.priority(0.9)
  }
  @posts.each do |p|
    xml.url {
      xml.loc("http://example.com/#{p.id.to_s}")
      xml.changefreq("weekly")
      xml.priority(0.5)
    }
  end
end

5) Commit and upload to heroku.