Paperclipを使用したファイルタイプのカスタムサムネイル
-
05-07-2019 - |
質問
Ruby on RailsでPaperclipを使用してアセットをモデルにアタッチします。これらのアセットは任意のファイルタイプにすることができ、現在サムネイルはアセットが画像の場合にのみ生成されます。アップロード時にファイルのサムネイルを生成するか、default_urlで何かを設定することにより、他のファイルに別のデフォルト画像を表示できるようにしたいのですが、これを支援するリソースが見つかりません。自分ではどこにも行きません。
私のモデルは次のとおりです:
class Asset < ActiveRecord::Base
has_attached_file :media,
:storage => :s3,
:s3_credentials => "#{RAILS_ROOT}/config/s3.yml",
:path => ":attachment/:id/:style.:extension",
:bucket => S3_BUCKET,
:styles => {:thumb => "75x75>", :large => "600x800>",
:whiny => false,
:default_url => "/images/:attachment/missing.jpg"
生成に失敗した場合、カスタムサムネイルを生成するためのリソースはありますか、またはデフォルトのURLの:content_typeなどにフォールバックしますか?ソースを調べましたが、どこにもアクセスできませんでした。
ありがとう!
解決
実際にこの機能を実装しました。 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のフォークに追加したものですが、独自のロジックで置き換えることができます(これを決定するための「標準」方法がわからない、おそらくパスを定義された「欠落」パスと比較するか、コンテンツタイプをデフォルトリスト[&quot; image / jpeg&quot;、&quot; image / png&quot;]などと比較するだけです。
とにかく、サムネイルスタイル(あなたの場合は: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
他のヒント
アセットから継承するファイルタイプがいくつかあります。ビデオと別の指定:
has_attached_file:media、...、:style =&gt; {....}