Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to turn .txt files uploaded with paperclip into raw text?

I added a document column to my Post model, so now I'm able to add txt files to it:

post.rb:

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

console:

 #<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">

So now, I would like to turn the content inside test.txt into raw text. So I can do something like this in my controller:

@post.content = [TEXT INSIDE test.txt]

Any suggestions?

like image 833
alexchenco Avatar asked Jan 02 '13 10:01

alexchenco


1 Answers

Using a before_save callback, then find the path, open the file and call File::read on the opened file.

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
like image 77
berkes Avatar answered Sep 18 '22 13:09

berkes