Quick and dirty initial avatars

A quick guide to adding initial avatars using the Avatarly gem

I wanted to make user avatars a little more personal on one of our applications recently without having to ask a user to upload a user avatar. I though about doing a Gmail style initial avatar and stumbled upon the avatarly gem.

First of all install the gem in your Gemfile and bundle:

gem 'avatarly'

When you use the Gem it give you a blob, then it’s up to you to save it off or display it. As our application has a small amount of users I’m just going to create it on the fly (hence the “quick and dirty” title), you may want to cache it if you think it will cause performance issues.

So in my user model I created an avatar method and Base64 encoded the result of the call to Avatarly. If you pass in no additional options it will create background colours for you on the fly I didn’t want this so I hardcoded the colour to suit my application.

def avatar
  Base64.strict_encode64(Avatarly.generate_avatar(username, opts={background_color: '#fc8848', font_color: '#ffffff'}))
end

As per the Avatarly README these are the options you can pass:

  • background_color (#AABBCC)
  • font_color (#AABBCC)
  • size (default: 32)
  • font (path to font - e.g. “#{Rails.root}/your_font.ttf”)
  • font_size (default: size / 2)
  • vertical_offset (default: 0)
  • format (default: png)
  • lang (language code if unicode aware upcase required - e.g: :tr, default: nil)

So now I have a Base64 encoded user initial avatar all I have to do to display it is call it in my view file:

<img src="data:image/png;base64,<%= current_user.avatar %>" class="header-dropdown__avatar" alt="">

And I end up with something like this:

Initial avatar

Recent posts View all

Web Development

Best Web Development Courses for Students

Some of the best web development courses to learn web development

Jekyll

Jekyll admin and frontmatter setup

Quick article creation with Jekyll Admin and frontmatter config