---
title: "扩展 Paperclip"
author: "hozaka"
date: "2009-01-23T19:24:06Z"
tags: []
slug: "paperclip"
draft: false
lastmod: "2009-01-23T19:35:08Z"
id: 320313
url: "https://hozaka.iteye.com/blog/320313"
---

Paperclip 是 Rails 的一个处理 attachment 的插件，相对于以往的 FileColumn 在灵活性和效率上更胜一筹，而且代码也比较好看。[这个视频](http://railscasts.com/episodes/134-paperclip) 简单的介绍了 Paperclip 的使用方法。

默认的设置，URL 的占位符中与模型本身相关的只有 id，但是一些情况下，你可能会更希望以其他形式来组织你的附件目录 - 比如以 SKU 来代替数据库记录的 id。这里我们暂不讨论这种做法的好坏，双方面的，好处是目录结构更具有维护性，坏处是万一以后升级数据库，SKU 加个前缀什么的…

Here we go!

使用 paperclip 需要在 model 中调用 [has\_attached\_file](http://dev.thoughtbot.com/paperclip/classes/Paperclip/ClassMethods.html#M000008) 方法，检查文档，有一些简单的使用样例，但是没有我们需要的。通过方法描述我们知道这个方法建立了一个 Paperclip::Attachment 对象，我们继续看文档。对象的方法很少，首先思考：应为我们需要配置的是 attachment 的 url 规则，那么应当是对应整个类而不是单个实力，因此我们只关注 Peperclip::Attachment 的类方法，只有两个。default\_options 没有描述，而且展开代码发现并不是我们需要的。

引用  
\# Paperclip::Attchment.interpolation  
A hash of procs that are run during the interpolation of a path or  
url. A variable of the format :name will be replaced with the return  
value of the proc named &ldquo;:name&rdquo;. Each lambda takes the attachment and  
the current style as arguments. This hash can be added to with your own  
proc if necessary.

这正是我们需要的，接下来的扩展就非常方便了：

```
# app/models/product.rb
class Product < ActiveRecord::Base
  has_attached_file :photo,
    :style => { :thumb => '64x64>' },
    :url => '/images/products/:to_param.:extension'
  
  def to_param
    return self.sku
  end
end

# config/initializers/paperclip.rb
Paperclip::Attachment.interpolations.merge!(
  :to_param => lambda { |attachment, style| attachment.instance.to_param }
)
```

在这里不直接使用 :sku 作为占位符而使用 :to\_param 是为了在其他模型中更加的灵活。