Extending the ImageAnalyzer

I’m looking to extend the ImageAnalyzer built into ActiveStorage to add some metadata around the location of faces in the image (if any). There doesn’t seem to be a way to hook into analysis at this point, so I just thought I’d check if that’s truely the case? It seems like it’d be useful to allow for additional analysis such as this. Currently I’m going for something like this:

module FaceAnalyser
  def metadata
    metadata = super

    read_image do |image|
      metadata[:primary_face] = [1, 1, 1, 1]
    end

    metadata
  end
end

module ActiveStorage
  class Analyzer::ImageAnalyzer < Analyzer
    prepend FaceAnalyser
  end
end

Would there be an appetite for adding the ability to register additional image analysers as a feature?

Check section 2.3.6 of my guide. It has the code to add extra image analyzers instead of extending or monkey patching existing ones.

Thanks @brenogazzola, I guess the only potential downside there is if the built in image analyser is changed to do more, your metadata method overwrites the method of the inherited class and so you’d miss out on the new analysis. Probably not a major. I suppose you could call super first?

    def metadata
      super.tap do |metadata|
        download_blob_to_tempfile do |file|
          metadata.merge! FaceDetection::Analyzer.new(file, blob.content_type).analyze
        end
      end
    end

Or something like that :slight_smile:

Yeah, guess super and merge is a good option. That said, if you are building custom analyzer you have specific needs you have handled and any extra fields that might be added later you would not be interested?

Yea, I guess that’s probably true. Hard to say what they’d like to add in the future anyway :slight_smile: