Monkey patching ActiveStorage::Attachment gets lost

I placed my ActiveStorage::AttachmentMonkeyPatch in /app/models/active_storage/
I've added a callback to get informed if the Attachment has changed. It works fine, all the time.

Maybe this is the issue.


Seems to have to do with delegate_missing_to, e.g.

delegate_missing_to :blob

https://github.com/rails/rails/blob/master/activestorage/app/models/active_storage/attachment.rb#L14

Going to where it's defined:

Anyway it might have to do with how attr_accessor works, I would try:

def url
  @url
end

def url=(url)
  @url = url
end

Instead of attr_accessor (which is a C function actually).

Otherwise a really really hacky way to solve this would be to check for ActiveStorage::Attachment.instance_methods.include?(:url) and monkey patch / include / prepend when not present.


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