在保存之前处理Paperclip图像

3

我正在使用Rails中的Paperclip保存图像上传,目前工作正常。

  has_attached_file :image, :styles => {
    :small => "80x90#"
  }

我会在创建模型时,将小图片的一份副本保存为base64编码字符串。

  before_update :encode_image
  
  private
  
  def encode_image
    self.base64 = ActiveSupport::Base64.encode64(open(self.image.path(:small)).to_a.join)
  end

上面的代码在更新时处理已保存的图像时效果很好。我想将此逻辑应用于模型保存之前但在图像被处理后触发的回调函数。
我原以为after_post_process会是我的救星,但此时路径尚未完全形成(缺少id)。
我漏掉了什么?
Rich
解决方法:
我的解决方法是执行以下操作,但每次更新模型时都运行编码程序似乎有些可惜。
  after_save :encode_image
  
  private
  
  def encode_image
    unless self.image.path(:small).blank?
      b64 = ActiveSupport::Base64.encode64(open(self.image.path(:small)).to_a.join)
      unless self.base64 == b64
        self.update_attribute :base64, b64
      end
    end
  end

谢谢分享你的解决方案。我最终也做了同样的事情,但是如果你在回调本身上放置条件,例如:after_save :encode_image, :unless => proc { |record| record.image.path(:small).blank? },你可以清理一下代码。 - vise
1个回答

1

我的解决方法是执行以下操作,但每次更新模型时都运行编码程序似乎有些浪费:

  after_save :encode_image

  private

  def encode_image
    unless self.image.path(:small).blank?
      b64 = ActiveSupport::Base64.encode64(open(self.image.path(:small)).to_a.join)
      unless self.base64 == b64
        self.update_attribute :base64, b64
      end
    end
  end

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接