如何将使用Paperclip上传的.txt文件转换为原始文本?

6

我在我的Post模型中添加了一个document列,这样我现在就能够将txt文件添加到它中:

post.rb:

has_attached_file :document
validates_attachment_content_type :document, :content_type => 'text/plain'

控制台:

 #<Post id: 92, content: "document upload test", user_id: 1, created_at: "2013-01-02 10:23:13", updated_at: "2013-01-02 10:23:13",
 title: "document upload test", document_file_name: "test.txt",
 document_content_type: "text/plain", document_file_size: 15,
 document_updated_at: "2013-01-02 10:23:13">

现在,我想将test.txt中的内容转换为纯文本,这样我就可以在控制器中执行以下操作:

@post.content = [test.txt中的文本]

有什么建议吗?

1个回答

5
使用 before_save 回调函数,然后找到路径,打开文件并在打开的文件上调用 File::read
class Post
  before_save :contents_of_file_into_body

  private
  def contents_of_file_into_body
    path = document.queued_for_write[:original].path
    content = File.open(path).read
  end
end

我在控制台尝试了这个,但是出现了这个错误:post.document.read.strip NoMethodError: undefined method 'read' for /system/posts/documents/000/000/092/original/test.txt?1357122193:Paperclip::Attachment - alexchenco
the wiki 的示例之后,我更新了问题。在读取文件之前需要打开它。 - berkes
谢谢!它起作用了(但必须将@post.content更改为self.content)。 - alexchenco
1
听起来真的很丑陋,应该呆在处理器里。或者至少,添加一个条件以避免在每次保存时执行此操作。 - apneadiving
apneadiving: 它确实很丑,但只是一个起点;它回答了确切的问题,而不是大多数想象中的边缘情况 :). 是的,当事情变得更加复杂(或测试要求如此)时,需要条件语句。目前,上下文太少了(也许文本文件总是存在?)无法编写最清洁的解决方案。 - berkes

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