Reputation: 79
How can I implement a callback (like before_save) on ActiveStorage::Blob?
I try to add the follow to my Initializers folder as blob.rb:
require 'active_storage/blob'
class ActiveStorage::Blob
before_save :do_something
def do_something
end
end
but getting error while running the server:
method_missing: undefined method `has_one_attached' for # (NoMethodError) Did you mean? has_attached_file
Any ideas? Different approach? Thanks.
Upvotes: 2
Views: 899
Reputation: 33
you can create a class like active_storage_blob_extension.rb in app/models
module ActiveStorageBlobExtension
extend ActiveSupport::Concern
included do
before_save :do_something
def do_something
# do something
end
end
end
and add it in config/application.rb
config.to_prepare do
ActiveStorage::Blob.send :include, ::ActiveStorageBlobExtension
end
the before_save callback will be called before is saved
Upvotes: 0
Reputation: 11
You can use https://github.com/rails/rails-observers
class ActiveStorageBlobObserver < ActiveRecord::Observer
observe "active_storage/blob"
def after_destroy(blob)
do_something
end
end
Upvotes: 1