Re: Handling File on Upload

Walter Lee Davis
2010-12-07T15:11:42Z

On Dec 6, 2010, at 6:50 PM, David Kahn wrote:

> You are mistaken, and although I came late to the Paperclip party, I
> can''t recall a time when it was true. You can edit the model
without
> modifying the image (just don''t upload another image) and
everything
> stays the same in the image, or you can upload a new image and it
> will overwrite the previous version. It''s all managed when you
save
> the model that the image is attached to.
>
> Right, but what I wanted was to be able to load a model instance,
> change the file (say I encrypt a portion of the text) and have
> Paperclip update that file on its own when I call model#save. I am
> pretty sure Paperclip does not do this. Right, you can re-save the
> file but it requires manual action beyond calling model#save.


If you code your transformation within a Paperclip Processor, you can
have any number of different transformed versions. Here''s one that
extracts the text from an uploaded PDF:

#lib/paperclip_processors/text.rb
module Paperclip
   # Handles extracting plain text from PDF file attachments
   class Text < Processor

     attr_accessor :whiny

     # Creates a Text extract from PDF
     def make
       src = @file
       dst = Tempfile.new([@basename,
''txt''].compact.join("."))
       command = <<-end_command
         "#{ File.expand_path(src.path) }"
         "#{ File.expand_path(dst.path) }"
       end_command

       begin
         success = Paperclip.run("/usr/bin/pdftotext -nopgbrk",
command.gsub(/\s+/, " "))
         Rails.logger.info "Processing #{src.path} to #{dst.path} in
the text processor."
       rescue PaperclipCommandLineError
         raise PaperclipError, "There was an error processing the text
for #{@basename}" if @whiny
       end
       dst
     end
   end
end


You call it from your model, like this:

#app/models/document.rb
...
   has_attached_file :pdf,:styles => { :text => { :fake =>
''variable'' } }, :processors => [:text]
...

The :fake => ''variable'' part is just in there to get the
offset
correct for the processors variable. I am not sure if it''s still
needed, but I have been doing it this way since early this summer.

Later, you can access that version of the file as you would any other
paperclip-attached model attribute. In this example, this might look
like document.pdf.url(:text). Your untouched original will always be
at document.pdf.url(:original).

Walter