Categories
BLOG

image of seeds

Klimo.io

Seeding Images From Unsplash

September 30, 2019 • 3 min read

Recently we’ve been making a more conscious effort to improve the quality of our seed data.

Firstly, to make it easier to onboard new team members. Secondly, to make the app ready for Review Apps. Certainly, it’s a great thing to be able to just re-seed your database if your local experiments go awry 😅

The kind of seeds I’ve seen over the years typically neglect images. They either use a minimal placeholder, use a few nicer images that are repeated over and over and checked into source control, or don’t do anything at all. How can we get this kind of awesomeness with almost no effort?

Unsplash

Unsplash is the internet’s source of freely useable images. It comes with a simple API we can use to seed our images from. Here’s how:

Sign up and create your app to get your API credentials.

Install the gem:

Initialize it (e.g. config/initializers/unsplash.rb ):

With that set up, you can fetch a collection of images with a single command:

This tells Unsplash to return page 1 of the results and use 25 records per page.

We use Shrine which makes it easy to use a remote URL as a source of attachment. To accomplish that, add the following to your attacher:

Here’s the final implementation used to seed data:

Rescuing from Unsplash::UnauthorizedError gives us the flexibility to make this an opt-in feature available if you set up your Unsplash ENV variables.

Careful observer will notice that this is not your typical structure of seeds.rb . In an effort to make our seeds more maintainable, we’ve broken it down into modules.

Every module has a single responsibility for seeding just one type of records. We keep these under db/seeds/*.rb .

This allows for a wonderfully clean seeds.rb file 🎉

Eager to learn about your experience with making seeds more useful!

Get beautiful images seed data with zero effort.