如何为ActiveStorage :: Variant添加方法?

时间:2019-06-24 09:31:59

标签: ruby-on-rails ruby overriding monkeypatching rails-activestorage

我想向ActiveStorage::Variant添加方法吗?

我有ActiveStorage :: Blob这个,当我修改代码而不重新加载服务器时,它就可以工作:

config/initializers/active_storage_direct_url.rb

module ActiveStorageDirectUrl
  def cloudfront_url(expires_at = nil)
    # xx
  end
end

ActiveSupport.on_load(:active_storage_blob) do
  ActiveStorage::Blob.include ActiveStorageBlobCachedUrl
end

但是问题是当我为ActiveStorage :: Variant执行此操作时。我尝试了这个:

ActiveSupport.on_load(:active_storage_blob) do
  ActiveStorage::Variant.include ActiveStorageVariantCachedUrl
end
ActiveSupport.on_load(:active_storage_variant) do
  ActiveStorage::Variant.include ActiveStorageVariantCachedUrl
end

但是在这两种情况下,在开发环境中,当我修改一些代码并且不重新启动服务器时,都会显示undefined method 'direct_url' for #<ActiveStorage::Variant:0x00007fc04fa45530>

当我重新加载rails server时,它仍然有效。 sidekiq也是一样,我需要重新加载它。

1 个答案:

答案 0 :(得分:0)

使用:

ActiveSupport::Reloader.to_prepare do
  ActiveStorage::Variant.include ActiveStorageVariantCachedUrl
end