Goodbye attachment_fu, hello Paperclip——开始体验
从哪儿开始个时候你已经准备好使用这个插件了,但我不会讲那些基本的如何在rails中使用Paperclip的知识,这些资料可以在官方网站 及 Jim Neath’sexcellent tutorial 或者RailsCast里找到。然而这里有些你应当了解新的特色跟提示,从而更好的使用Paperclip。
保护你的属性
如果你使用过attachment_fu,你可能已经知道旧版本的didn’t like attr_protected.好消息是不但attachment_fu最近得到了修复,Paperclip将attr_protected与attr_accessible也应用的很好。安全起见,你应该将你的file_name,content_type,size等属性保护在你的model里,例如:
has_attached_file :logoattr_protected :logo_file_name, :logo_content_type, :logo_sizeAttaching in migrations or the Rails console
Attaching a file to a model in a migration or when using the Railsconsole is much easier with Paperclip than it is with attachment_fu.All you need to do is open a File object and assign it to theattachment attribute of the model:
使用Paperclip向一个处于migration的model类添加一个文件或者当使用Rails控制台使要比attachment_fu要容易的多,你所需要的只是打开一个文件对象,将它赋予这个model的文件属性即可:
user = User.firstFile.open('path/to/image.png') { |photo_file| user.photo = photo_file }user.save
这段代码能运行在大多数系统中,但不包括windows,在windows中,这种赋值会造成如下错误:
identify: no decode delegate for this image format `C:/DOCUME~1/ROB~1.CML/LOCALS~1/Temp/stream.2692.0'.
除了这段含义模糊的信息,文件也不会被正常添加,并且不会生成缩略图。幸运的是解决方案很简单(尽管我也挠头抓腮好一会儿才将它想通):将文件的读写模式改为二进制,从而让windows不把它当成一个文本文件。
user = User.firstFile.open('path/to/image.png', 'rb') { |photo_file| user.photo = photo_file }user.saveDiscarding an uploaded image
当一个图片被上传后,Paperclip会使用它的original 风格 名字来保存它。尽管不能让paperclip扔掉原来的图片,但可以定义你自己的original风格以便Paperclip将来使用。例如,如果你的model包含如下代码:
has_attached_file :photo, :styles => { :original => '250x250>',:small => '50x50' }
这样即便是一个大图片(例如:1600X1600)被上传,它也不会保存到你的电脑上。你仍旧会得到一个原始文件,但它被压缩到250X250,从而减少了需要的存储空间。
Styles can be Procs too
大多数时候你很有可能要传递 geometry strings给has_attached_file方法的option项,但有一个很好的特性是你可以传递一个Proc,从而提供动态的geometry strings生成。例如,你有一个model,它有两个属性:photo_width,photo_height,这两个属性你可以改变它们的值。当你想生成一个定制的缩略图,paperclip允许你这样做:
has_attached_file :photo, :styles => { :original => '250x250>', :small => '50x50', :custom => Proc.new { |instance| "#{instance.photo_width}x#{instance.photo_height}>" } }
正如你看到的那样,Proc接受一个附件所在的对象作为一个参数,返回一个使用photo_width跟photo_height生成的geometry string。向你的model的before_save回调函数里添加一个对附件对象的reprocess!方法的调用,这样可以在这些属性更新后,再生成缩略图。
页:
[1]