Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I add gravatar/identicons into Ruby on Rails?

I have looked at the following, but they aren't clear, particularly the reference to DataMapper and gem dependencies.

All I want as an outcome is to be able to take my @user.email value that is in a |do| loop and display a gravatar where the identicon is set to "y" -- in other words, those cute seemingly random drawings!

But when I look at what is available, it isn't clear what to do -- particularly the references to DataMapper and gem dependencies.

http://github.com/chrislloyd/gravtastic/tree/master

I am playing around with this, but I wanted to get feedback from others before diving too deep!

http://www.thechrisoshow.com/2008/10/27/adding-gravatars-to-your-rails-apps

I installed woods gravatar plugin:

http://github.com/woods/gravatar-plugin/tree/master which is the same as the one referred below...however, I get an error when I type in:

<%= gravatar_for @user %>

The error is:

undefined method `gravatar_for' for #<ActionView::Base:0x474ddf4>
like image 223
Satchel Avatar asked Apr 21 '09 02:04

Satchel


2 Answers

Put this code in your ApplicationHelper so that gravatar_for is available in all views.

def gravatar_for email, options = {}
    options = {:alt => 'avatar', :class => 'avatar', :size => 80}.merge! options
    id = Digest::MD5::hexdigest email.strip.downcase
    url = 'http://www.gravatar.com/avatar/' + id + '.jpg?s=' + options[:size].to_s
    options.delete :size
    image_tag url, options
end

In views:

<%= gravatar_for 'my@mail' %>
<%= gravatar_for 'my@mail', :size => 48 %>
<%= gravatar_for 'my@mail', :size => 32, :class => 'img-class', :alt => 'me' %>

I refined slant's solution. Following Gravatar guidelines, e-mails should be trimmed and lowercased before hashing. Also, it seems require 'digest' isn't needed (tested on Rails 3).

like image 170
Nowaker Avatar answered Sep 28 '22 07:09

Nowaker


Not to repeat too much, but instead to give a more detailed answer:

As Sam152 said, you must create an MD5 hash from the user's email address which is then used in a GET request to the gravatar server.

The easiest way to gain access to MD5 hashes is through Digest, part of the ActionPack (inside ActionView) gem. Place the following in 'config/environment.rb':

require 'digest'

Now you only need to use the following where you wish to display the user's gravatar:

image_tag("http://www.gravatar.com/avatar.php?gravatar_id=#{Digest::MD5::hexdigest(@user.email)}", :alt => 'Avatar', :class => 'avatar')

This requires no additional gems and you can create a helper as needed if all you require is pulling in the user's gravatar.

like image 21
slant Avatar answered Sep 28 '22 07:09

slant