Active Storage: Adding a custom Analyzer for unsupported image type

When you add an attachment with Active Storage, Rails kicks off a background job to analyse the attachment. You can add your own analyzer – but the documentation is very thin on the details.

One of my apps uploads .heic image files. Unfortunately as of Rails 5; this triggers a crash in the image analyzer because imageMagick can’t yet handle this filetype.

My solution to the crash is to create a custom analyzer that handles image/heic files, and returns no metadata.

# lib/models/heic_analyzer.rb

class HeicAnalyzer < ActiveStorage::Analyzer

	def self.accept?(blob)
	  blob.content_type == "image/heic"
	end

	def metadata
	  {}
	end

end

Make sure the class is loaded

# application.rb

config.autoload_paths << "#{Rails.root}/lib/models"

then add the Heic analyzer to active storage

# config/initializers/image_analyzer.rb

Rails.application.config.active_storage.analyzers.prepend HeicAnalyzer

That’s it. Rails now handles my .heic attachment without crashing