ruby-on-railsrubyruby-on-rails-5monkeypatchingrails-activestorage

Monkey patching ActiveStorage::Attachment gets lost


So I decided to add an url attr_accessor to ActiveStorage::Attachment objects.

In development the patch holds for a while until it seems to "have been lost". Meaning it works for few minutes, then it does not work anymore. Then I need to restart the server in order to get the patch applied again. I believe I am not patching correctly and I would need advises in that mater.


Here is what I tried:

lib/ext/active_storage/attachment.rb

First try :

module ActiveStorageUrl
  extend ActiveSupport::Concern

  included do
    attr_accessor :url
  end
end

ActiveStorage::Attachment.send :include, ActiveStorageUrl

Second try

class ActiveStorage::Attachment < ActiveRecord::Base
  attr_accessor :url
end

And by the way in both case it's loaded with this:

config/initializers/monkey_patches.rb

require 'ext/active_storage/attachment'

So when it work I have no error message, but after a while the patch "diseapear" (lacking better terms), and I get the following error, telling me my attr_accessor is not there anymore. Rails must have reloaded ActiveStorage classes and my patch is lost.

Module::DelegationError in Products#images
url delegated to blob, but blob is nil

Solution

  • You are probably losing your monkey patch because the code gets reloaded and your ext/active_storage/attachment isn't re-required.

    You can tell Rails to run a callback at startup and every time code is reloaded like this.

    Rails.configuration.to_prepare do
      require 'ext/active_storage/attachment'
    end