【问题标题】:Using Rails Paperclip gem to preprocess file before saving在保存之前使用 Rails Paperclip gem 预处理文件
【发布时间】:2012-10-25 15:32:27
【问题描述】:

我在 Rails 3.2 应用程序上使用 Paperclip gem,用户可以在其中上传包含图像和其他信息的专用文件类型(我们称之为“.elf”文件)。

我已经编写了通过一个名为 ElfObject 的类从 elf 文件中提取图像所需的所有代码,并且在应用程序的控制台中进行测试时效果很好。我想要做的是在 Paperclip 将其保存到 AWS S3 之前从 .elf 文件中提取图像和其他数据,将其他数据存储在模型中,然后仅将图像对象保存为 S3 上的 Paperclip 附件。下面是模型中的相关代码:

class Photo < ActiveRecord::Base

  validates_attachment :attachment,
        :presence => true

  has_attached_file :attachment,
    :storage => :s3,
    [[S3 credentials removed]]

  before_attachment_post_process :import_photo

  attr_accessible :name, :attachment, :properties

  def import_photo
    if attachment_file_name =~ %r{^*\.elf$}
      origfile = attachment.queued_for_write
      elf = ElfObject.read(origfile)
      properties = elf.get_properties 
      attachment = elf.image.write "image_for_#{attachment_file_name}.png"
      save!      
    end
  end

当我尝试在应用程序上以这种方式上传时,它会从 elf = ElfObject.读取(原始文件)。如果我尝试 elf = ElfObject.read(origfile.path) 之类的方法,我会得到 NoMethodError (undefined method `path' for #)

显然,我不完全了解如何在文件发布之前从 Paperclip 访问文件 - 关于我哪里出错以及如何修复它的任何想法?

【问题讨论】:

    标签: ruby-on-rails paperclip


    【解决方案1】:

    似乎问题正是错误所说的......origfileHash,而不是String

    如果是这种情况,那么attachment.queued_for_write 返回一个Hash,这意味着您需要找到保存文件路径字符串的键。

    origfile = attachment.queued_for_write
    p origfile.inspect #print it out so you can figure out what key holds the path
    

    编辑后的答案试试这个:

    def import_photo
      if attachment_file_name =~ %r{^*\.elf$}
        origfile = attachment.queued_for_write[:original]
        elf = ElfObject.read(origfile.path)
        properties = elf.get_properties 
        attachment = elf.image.write "image_for_#{attachment_file_name}.png"
        save!      
      end
    end
    

    【讨论】:

    • 谢谢。 p origfile.inspect 的输出是 "{:original=>Paperclip::UploadedFileAdapter: SymphonyWeb47945_1.ELF}"。我之前尝试过类似的东西,但我不知道如何处理哈希中的对象。
    • 或者,更重要的是,我不知道如何将 Paperclip::UploadedFileAdapter: SymphonyWeb47945_1.ELF 作为可以被 ElfObject 读取的文件。也许我只是想在 Paperclip 中以错误的方式解决这个问题?
    • attachment.queued_for_write 代替 attachment.to_file.path 有效吗?
    • 当我尝试得到 NoMethodError (undefined method `to_file' for #<:attachment:0x007fe14dbe7748>)
    • 根据comments left on the answer hereto_file 在 Paperclip 中被弃用,取而代之的是 queued_for_write。仅供参考。
    猜你喜欢
    • 1970-01-01
    • 2014-07-17
    • 1970-01-01
    • 1970-01-01
    • 2012-03-10
    • 2013-05-09
    • 2011-02-17
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多