微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

ActiveStorage:旧网址仍然要求弃用:variation_key

如何解决ActiveStorage:旧网址仍然要求弃用:variation_key

最近我从 Rails 6.0.3.4 升级到 6.1.3。 ActiveStorage 已弃用 combine_options,我已将其从我的应用中清除。所有新请求都按预期工作。 Internet Bots(Facebook、Google 等)将 URL 缓存到网站(如我的)上托管的图像。根据我的 Rollbar 记录,他们每天会要求这些。

应加载 ActiveStorage 附件的缓存 URL 在 URL 中包含旧的 variation_key。当 blob 想要使用解码后的 variation_key 加载时,我看到 combine_options 仍然存在。这会抛出一个 500 Internal Server Error with ArgumentError (Active Storage's ImageProcessing transformer doesn't support :combine_options,as it always generates a single ImageMagick command.):

有什么办法可以阻止这些错误出现吗?

Rails 版本:6.1.3。 红宝石版本:2.7.2p137

解决方法

我已经使用一些中间件解决了这个问题。这将拦截所有传入的请求,扫描它们是否为 ActiveStorage url,找到不推荐使用的 combine_options 并返回 404 not found。这段代码也会报错是当前环境正在开发中,这样就不会不小心再引入过时的代码了。

对于那些可能有同样问题的人,这是代码。

应用程序.rb

require_relative '../lib/stopper'
config.middleware.use ::Stopper

lib/stopper.rb

class Stopper
  def initialize(app)
    @app = app
  end

  def call(env)

    req = Rack::Request.new(env)
    path = req.path

    if problematic_active_storage_url?(path)
      if ENV["RACK_ENV"] == 'development'
        raise "Problematic route,includes deprecated combine_options"
      end
      [404,{},['not found']]
    else
      @app.call(env)
    end
  end

  def problematic_active_storage_url?(path)
    if active_storage_path?(path) && !valid_variation_key?(variation_key_from_path(path))
      return true
    end
    false
  end

  def active_storage_path?(path)
    path.start_with?("/rails/active_storage/representations/")
  end

  def variation_key_from_path(path)
    if path.start_with?("/rails/active_storage/representations/redirect/")
      path.split('/')[6]
    elsif path.start_with?("/rails/active_storage/representations/")
      path.split('/')[5]
    end
  end

  def valid_variation_key?(var_key)
    if decoded_variation = ActiveStorage::Variation.decode(var_key)
      if transformations = decoded_variation.transformations
        if transformations[:combine_options].present?
          return false
        end
      end
    end
    true
  end
end

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。