Ben*_*enj 9 ruby monkeypatching ruby-on-rails ruby-on-rails-5 rails-activestorage
因此,我决定向urlActiveStorage :: Attachment对象添加attr_accessor。
在开发中,该补丁会保留一段时间,直到看起来“已丢失”为止。这意味着它可以工作几分钟,然后不再工作。然后,我需要重新启动服务器才能再次应用补丁。我认为我没有正确打补丁,因此我需要在该方面提供建议。
这是我尝试过的:
lib / ext / active_storage / attachment.rb
第一次尝试 :
module ActiveStorageUrl
extend ActiveSupport::Concern
included do
attr_accessor :url
end
end
ActiveStorage::Attachment.send :include, ActiveStorageUrl
Run Code Online (Sandbox Code Playgroud)
第二次尝试
class ActiveStorage::Attachment < ActiveRecord::Base
attr_accessor :url
end
Run Code Online (Sandbox Code Playgroud)
顺便提一下,在这两种情况下,它都装有:
config / initializers / monkey_patches.rb
require 'ext/active_storage/attachment'
Run Code Online (Sandbox Code Playgroud)
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
Run Code Online (Sandbox Code Playgroud)
我将我的ActiveStorage::AttachmentMonkeyPatch 放在/app/models/active_storage/
我添加了一个回调来通知附件是否已更改。它一直工作正常。
也许这就是问题所在。
您可能会丢失您的猴子补丁,因为代码被重新加载并且您的ext/active_storage/attachment不再需要。
您可以告诉 Rails 在启动时以及每次重新加载代码时运行回调,如下所示。
Rails.configuration.to_prepare do
require 'ext/active_storage/attachment'
end
Run Code Online (Sandbox Code Playgroud)