Search code examples
ruby-on-railsrubyspringoverridingmonkeypatching

How to override one method from Rails Framework?


How to override a method in Rails?

To be more specific, I am on 6.0.0.rc1, and I want this commit, but it will be available only on 6.1 : https://github.com/rails/rails/pull/36072/files

I want to override the private method def read_image from

module ActiveStorage
  class Analyzer::ImageAnalyzer < Analyzer
    private
      def read_image

How would you do it, in which Rails folder?


Solution

  • Since this is Ruby you can just do it by putting that exact code in something like config/initializers/active_storage_read_image.rb:

    module ActiveStorage
      class Analyzer::ImageAnalyzer < Analyzer
      private
        def read_image
          # My implementation here
        end
      end
    end
    

    You may want to add a reminder test in there like this:

    if (Rails.version.starts_with?('6.1'))
      Rails.logger.warning("This patch may not be required in Rails 6.1")
    end