I want to extend the class ActiveStorage::Attachment and add an enum attribute for visibility of attachments.
My initial approach was to create a new file attachment.rb in the \app\models directory as follows.
class ActiveStorage::Attachment < ActiveRecord::Base
    enum visibility: [ :privately_visible, :publicly_visible]
end
This doesn't work.
Any suggestions are welcome. What's the Rails way to extend classes?
Update
I have a solution that works partially now. For this, I have created an extension active_storage_attachment_extension.rb and placed it in \lib
module ActiveStorageAttachmentExtension
  extend ActiveSupport::Concern
  included do
    enum visibility: [ :privately_visible, :publicly_visible]
    def describe_me
      puts "I am part of the extension"
    end
  end
end
The extension is loaded during initialization in extensions.rb
ActiveStorage::Attachment.send(:include, ::ActiveStorageAttachmentExtension)
Unfortunately, it is only working partly: While the enum methods publicly_visible? and privately_visible? are available in the views, they are not available in the controller. When invoking any of the methods in the controller, then the enum seems to have disappeared. I get a "NoMethodError - undefined method" error. Surprisingly, once the enum methods are called once in the controller, they are also not available any more in the views. I assume that the ActiveStorage::Attachment class gets reloaded dynamically and that the extensions are lost as they are only added during initialization.
Any ideas?
This works for me in Rails 6.
# frozen_string_literal: true
module ActiveStorageAttachmentExtension
  extend ActiveSupport::Concern
  included do
    has_many :virus_scan_results
  end
end
Rails.configuration.to_prepare do
  ActiveStorage::Attachment.include ActiveStorageAttachmentExtension
end
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With