Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extending ActiveStorage::Attachment - Adding custom fields

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?

like image 353
Patrick Frey Avatar asked Jun 09 '18 03:06

Patrick Frey


1 Answers

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
like image 100
Martin Streicher Avatar answered Sep 22 '22 15:09

Martin Streicher