Using paperclip with local files

1,570 views
Skip to first unread message

I Go by Ed

unread,
Dec 30, 2008, 11:11:04 AM12/30/08
to Paperclip Plugin
I love Paperclip and I've used it successfully in a few projects now.
I have a new project with slightly different requirements and I'm a
bit stuck.

Basically, I need my paperclip attachment to come from a temp file
instead of a form field.

I'm creating an image of text (via ImageMagick) and I want that image
to be the attachment.

How would I do this?

Here's code from my model that I've tried (with no success):



after_create :make_image

has_attached_file :image,
:styles => {:thumb=> "100x100#", :small => "150x150>", :medium
=> "250x250>", :large => "625x300>" },
:path => ":rails_root/public/
uploads/:attachment/:id/:style_:basename.:extension",
:url => "/uploads/:attachment/:id/:style_:basename.:extension"


def make_image

file = File.join(Dir.tmpdir, "#{self.id}_image.png")

`convert -background lightblue -fill blue -font Arial -pointsize
72 label:some-text #{file}`

io = File.read(file)
self.image = io

end

Jonathan Yurek

unread,
Dec 30, 2008, 2:49:49 PM12/30/08
to papercli...@googlegroups.com
From what it looks like, there's only one tiny change needed, and
that's to switch your "File.read(file)" to "File.new(file)". Paperclip
is capable of reading a file off the filesystem just as easily as an
upload.

Hope that helps.
--
Jonathan Yurek, Founder and CTO
thoughtbot, inc.
organic brains. digital solutions.

617.482.1300 x114
http://www.thoughtbot.com/

I Go by Ed

unread,
Dec 30, 2008, 3:04:43 PM12/30/08
to Paperclip Plugin
I did File.read because I created the file on the previous lines via
ImageMagick ... at least I thought I did :)

So, my thought process is:
1. build the full path to the file using the temp dir and a file name
based on the record ID
2. use ImageMagick to create an image (of text) and save it with step
1's path/name
3. assign the paperclip image attachment to be the file I created

Am I going about this wrong?

Thanks for the help

Jonathan Yurek

unread,
Dec 30, 2008, 3:44:51 PM12/30/08
to papercli...@googlegroups.com
No, that's not wrong. After you have the file that IM spits out, you
can assign that to your attachment as a File object. File.read will
load the data from the file, but Paperclip only needs a File instance,
so File.new is what you want to use: "self.image = File.new(file)".
Reply all
Reply to author
Forward
0 new messages