Have you ever created an application where users are trusted to upload their own avatars? Wouldn’t it be great if there was an easy way to ensure the avatar contains a person’s face?

Has Face is a neat little gem that uses the face.com API to ensure that an image contains a persons face. It’s very simple to use and can be easily integrated into an existing rails application.

To get started add the has_face gem to your Gemfile and run a bundle install

Can’t see this Gist? View it on Github!

Run the generator to copy over an initializer:

Can’t see this Gist? View it on Github!

The initializer should look something like this:

Can’t see this Gist? View it on Github!

Now we’ll need to make a face.com developer account. You can signup for a free account over at face.com. Once you have signed up, place your API key and API secret in the initializer config.

The last option in the initializer (skip_validation_on_error) will change the behavior of has_face when an error occurs. If set to true, when an error occurs a warning will be logged to the logfile with detailed information about the failure and face validation will be skipped. This can be useful if you want your application to function if the API service is not reachable. If the value is false then an exception will be raised when an API call fails, this will allow you to manually handle the exception yourself, please check the documentation for details on the errors raised.

Once the initializer settings are setup then we can add face validation to a model. In the example below I’m using carrierwave to attach the image to the model but other image attachment gems should also work fine (anything that correctly responds to `path` should be OK).

Can’t see this Gist? View it on Github!

That’s it, that’s all we need to have a functioning face validator. There are a few other options that I haven’t covered here in this short guide, please consult the readme for more detailed information.