The project is in a healthy, maintained state
Use blurhashes to lazy load ActiveStorage images
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
 Dependencies

Development

Runtime

>= 7.1.3.4
>= 7.1.3.4
~> 0.1.0
 Project Readme

ActiveStorage::Blurhash

A blurhash integration for images stored in ActiveStorage.

Motivation

Elimination of layout shift and speeding up First/Largest Contentful Paint are among the primary goals for improving Core Web Vitals. For both scenarios, lazy loading images while displaying a temporary Blurhash before swapping it out for the actual image is a great way to enhance the loading experience and perceived performance.

Usage

Suppose we have a simple Person model containing an avatar attachment:

class Person < ApplicationRecord
  has_one_attached :avatar
end

Simply swap out image_tag for blurhash_image_tag when displaying it:

<%= blurhash_image_tag person.avatar %>

This will create a wrapper <div> containing a <canvas> that is going to be painted with the respective blurhash.

Make sure to run the install generator and backfill any existing attachments (see below). New attachments should be automatically analyzed to include the blurhash metadata.

Installation

Add the library to your application's Gemfile:

gem "active_storage-blurhash"

You will also need to add the "image_processing" gem to your Gemfile:

gem "image_processing"

And then execute:

$ bundle

Install the JavaScript packages and blurhash snippet:

$ bin/rails g active_storage:blurhash:install

Important

Consider that, to make everything work, you need libvips or MiniMagick installed on your system.

Backfilling

Chances are you already have a large assortment of ActiveStorage attachments. In this case, we can help you out with a backfill rake task that re-analyzes all existing image blobs:

$ bin/rails active_storage_blurhash:backfill

If you want to throttle it, you can change the batch size using the BATCH_SIZE environment variable (default is 1000):

$ BATCH_SIZE=50 bin/rails active_storage_blurhash:backfill

Note that for each blob an AnalyzeJob will be appended to your job processor queue.

License

The gem is available as open source under the terms of the MIT License.

Other gems & packages

  • avo - Build Content management systems with Ruby on Rails
  • class_variants - Easily configure styles and apply them as classes. Very useful when you're implementing Tailwind CSS components and call them with different states.
  • prop_initializer - A flexible tool for defining properties on Ruby classes.
  • stimulus-confetti - The easiest way to add confetti to your StimulusJS app

Try Avo ⭐️

If you enjoyed this gem try out Avo. It helps developers build Internal Tools, Admin Panels, CMSes, CRMs, and any other type of Business Apps 10x faster on top of Ruby on Rails.