Skip to content

Instantly share code, notes, and snippets.

@emad-elsaid
Created March 7, 2014 13:07
Show Gist options
  • Save emad-elsaid/9411128 to your computer and use it in GitHub Desktop.
Save emad-elsaid/9411128 to your computer and use it in GitHub Desktop.
Gravatar image url generator simple method Gravatar image url generator simple method
#!/usr/bin/env ruby
require 'digest/md5'
require "addressable/uri"
# this is based on gravatar image API
# https://en.gravatar.com/site/implement/images/
# options :
# size : <integer> size of image
# default: <string> url of image if email not found or:
# * 404
# * mm
# * identicon
# * monsterid
# * wavatar
# * retro
# * blank
# forcedefault: "y" force default image to load
# rating: <string> one of the values : g, pg, r, x
def gravatar email, *options
email_md5 = Digest::MD5.hexdigest email
unless options.empty?
params = Addressable::URI.new
params.query_values = options.first
params_query = "?#{params.query}"
end
"http://www.gravatar.com/avatar/#{email_md5}#{params_query}"
end
puts gravatar('blazeeboy@gmail.com')
puts gravatar(
'blazeeboy@gmail.com',
size: 200,
default: 'https://pbs.twimg.com/media/BheUcQMIAAA0Gns.jpg:large'
)
@brunojabs
Copy link

Hi there!

I don't understand why you used "Addressable" and used options.first.

I would do:

def gravatar email, options={}
  email_md5 = Digest::MD5.hexdigest email
  params_query = "?#{options.to_param}" unless options.empty?
  "http://www.gravatar.com/avatar/#{email_md5}#{params_query}"
end

What do you think?

@emad-elsaid
Copy link
Author

you're right about using options={} i forgot this syntax, but about using to_param this is defined inside rails env, i prefer to use ruby standard library of tiny gems like addressable, it would be great if you forked the gist and made your enhanced version. :)

@brunojabs
Copy link

you're right, i was sure that to_param is defined in ruby core, sorry! haha

I made a research and found a standard lib in ruby (URI) that do this parsing.

Here is my version:
https://gist.github.com/brunojabs/9413351

Thanks! (:

@dahal
Copy link

dahal commented Mar 7, 2014

#!/usr/bin/env ruby
require 'digest/md5'

def gravatar_url(email)
  gravatar_id = Digest::MD5.hexdigest(email.downcase)
    "http://gravatar.com/avatar/#{gravatar_id}.png"
end

puts gravatar_url("pdahal@outlook.com")

I would prolly do this.
https://gist.github.com/dahal/9419572

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment