私は実際にこれとまったく同じ機能を実装しました。Paperclip はすべての画像と PDF のサムネイルを生成し、MS Word、Excel、HTML、TXT ファイルなどのカスタム サムネイル アイコンを追加しました。
私の解決策はかなり簡単です。私のモデルAttachment
(あなたの場合Asset
)では、次のメソッドを定義しました:
def thumbnail_uri(style = :original)
if style == :original || has_thumbnail?
attachment.s3.interface.get_link(attachment.s3_bucket.to_s, attachment.path(style), EXPIRES_AFTER)
else
generic_icon_path style
end
end
これは、S3 に保存されているサムネイルへの URL、またはアセットのコンテンツ タイプに基づく汎用 PNG アイコンへのローカル パスのいずれかを返します (以下で説明します)。このhas_thumbnail?
メソッドは、このアセットのサムネイルが生成されているかどうかを判断します。これは、Paperclip の独自のフォークに追加したものですが、独自のロジックに置き換えることができます (パスを定義済みの「欠落」パスと比較するか、パスを比較する「標準的な」方法がわからない場合もあります)。コンテンツ タイプをデフォルト リスト ["image/jpeg"、"image/png"] などと比較するだけです)。
とにかく、サムネイルスタイル(この場合は :thumb と :large )とコンテンツタイプの両方に基づいて、パスを汎用アイコンに戻すメソッドを次に示します。
# Generates a path to the thumbnail image for the given content type
# and image size.
#
# e.g. a :small thumbnail with a content type of text/html, the file name
# would have the filename icon.small.text.html.png
#
# If no such thumbnail can be found a generic one is returned
def generic_icon_path(style = image.default_style)
url = "/images/attachments/icon.#{style.to_s}.#{attachment_content_type.sub('/', '.')}.png"
if File.exists? "#{RAILS_ROOT}/public/#{url}"
url
else
"/images/attachments/icon.#{style.to_s}.default.png"
end
end
次に、新しいサムネイルを追加するには、PNG ファイルを/images/attachments/
正しいファイル名規則で追加します。私のサムネイル スタイルは :small と呼ばれ、Word、Excel、およびプレーン テキストのスタイルを定義しているので、現時点では次のようになっています。
icon.small.application.msword.png
icon.small.text.plain.png
icon.small.application.vnd.ms-excel.png
icon.small.application.vnd.openxmlformats-officedocument.spreadsheetml.sheet.png
icon.small.application.vnd.openxmlformats-officedocument.wordprocessingml.document.png
コンテンツ タイプがサポートされていない場合は、一般的な「すべてをキャッチ」アイコンが表示されます。
icon.small.default.png