Gizp列使用ActiveModel :: Type :: Binary

时间:2017-06-23 11:17:17

标签: ruby-on-rails ruby activemodel

我正在尝试使用ActiveModel :: Type :: Binary库将base64编码数据gzip存储在postgres中。

create_table :documents do
  t.binary :document_data
end

我的模特:

class Document < ApplicationRecord
  class DocumentData < ActiveModel::Type::Binary
    def serialize(value)
      super compress(value)
    end

    def deserialize(value)
      super decompress(value)
    end

    private

    def compress(value)
      ActiveSupport::Gzip.compress(Base64.decode64(value))
    end

    def decompress(value)
      Base64.strict_encode64(ActiveSupport::Gzip.decompress(value))
    end

  end

  attribute :document_data, DocumentData.new
end

serialize方法似乎按预期工作,但是当调用deserialize时,value的编码方式不同,Gzip.decompress失败。

感谢您的帮助。

修改

如果记录为PG::Connection.unescape_bytea,我在ActiveRecord::ConnectionAdapters::PostgreSQL::OID::Bytea#deserialize中找不到Type::Binary::Data。我在PG::Connection.unescape_bytea之前打电话给decompress并且它有效,但我对这个解决方案不满意,所以我现在暂不开放。

0 个答案:

没有答案