{"id":13395066,"url":"https://github.com/thoughtbot/paperclip","last_synced_at":"2025-10-05T17:31:50.006Z","repository":{"id":390771,"uuid":"8393","full_name":"thoughtbot/paperclip","owner":"thoughtbot","description":"Easy file attachment management for ActiveRecord","archived":true,"fork":false,"pushed_at":"2023-07-13T17:57:58.000Z","size":3579,"stargazers_count":8998,"open_issues_count":54,"forks_count":2427,"subscribers_count":177,"default_branch":"main","last_synced_at":"2025-01-21T06:32:47.910Z","etag":null,"topics":[],"latest_commit_sha":null,"homepage":"https://thoughtbot.com","language":"Ruby","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"other","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/thoughtbot.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":"CONTRIBUTING.md","funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null}},"created_at":"2008-04-10T19:58:20.000Z","updated_at":"2025-01-20T00:57:42.000Z","dependencies_parsed_at":"2022-07-14T12:17:22.123Z","dependency_job_id":"29a598db-9e18-48a5-a703-85332c3c198f","html_url":"https://github.com/thoughtbot/paperclip","commit_stats":{"total_commits":1782,"total_committers":463,"mean_commits":"3.8488120950323976","dds":0.7239057239057238,"last_synced_commit":"c769382c9b7078f3d1620b50ec2a70e91ba62ec4"},"previous_names":[],"tags_count":103,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/thoughtbot%2Fpaperclip","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/thoughtbot%2Fpaperclip/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/thoughtbot%2Fpaperclip/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/thoughtbot%2Fpaperclip/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/thoughtbot","download_url":"https://codeload.github.com/thoughtbot/paperclip/tar.gz/refs/heads/main","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":235075586,"owners_count":18931909,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":[],"created_at":"2024-07-30T17:01:40.870Z","updated_at":"2025-10-05T17:31:44.976Z","avatar_url":"https://github.com/thoughtbot.png","language":"Ruby","readme":"Paperclip\n=========\n\n# Deprecated\n\n**[Paperclip is deprecated]**.\n\nFor new projects, we recommend Rails' own [ActiveStorage].\n\nFor existing projects, please consult and contribute to the migration guide,\navailable [in English], [en español], and as [a video] recorded at RailsConf\n2019. You may also prefer [an alternative migration tutorial used by\nDoorkeeper][].\n\nAlternatively, for existing projects, [Kreeti] is maintaining [kt-paperclip],\nan ongoing [fork of Paperclip].\n\nWe will leave the Issues open as a discussion forum _only_. We do _not_\nguarantee a response from us in the Issues. All bug reports should go to\nkt-paperclip.\n\nWe are no longer accepting pull requests _except_ pull requests against the\nmigration guide. All other pull requests will be closed without merging.\n\n[Paperclip is deprecated]: https://robots.thoughtbot.com/closing-the-trombone\n[ActiveStorage]: http://guides.rubyonrails.org/active_storage_overview.html\n[in English]: https://github.com/thoughtbot/paperclip/blob/master/MIGRATING.md\n[en español]: https://github.com/thoughtbot/paperclip/blob/master/MIGRATING-ES.md\n[a video]: https://www.youtube.com/watch?v=tZ_WNUytO9o\n[Kreeti]: https://www.kreeti.com/\n[kt-paperclip]: https://rubygems.org/gems/kt-paperclip\n[fork of Paperclip]: https://github.com/kreeti/kt-paperclip\n[an alternative migration tutorial used by Doorkeeper]: https://www.tokyodev.com/2021/03/23/paperclip-activestorage/\n\n# Existing documentation\n\n## Documentation valid for `master` branch\n\nPlease check the documentation for the paperclip version you are using:\nhttps://github.com/thoughtbot/paperclip/releases\n\n---\n\n[![Build Status](https://secure.travis-ci.org/thoughtbot/paperclip.svg?branch=master)](http://travis-ci.org/thoughtbot/paperclip)\n[![Dependency Status](https://gemnasium.com/thoughtbot/paperclip.svg?travis)](https://gemnasium.com/thoughtbot/paperclip)\n[![Code Climate](https://codeclimate.com/github/thoughtbot/paperclip.svg)](https://codeclimate.com/github/thoughtbot/paperclip)\n[![Inline docs](http://inch-ci.org/github/thoughtbot/paperclip.svg)](http://inch-ci.org/github/thoughtbot/paperclip)\n[![Security](https://hakiri.io/github/thoughtbot/paperclip/master.svg)](https://hakiri.io/github/thoughtbot/paperclip/master)\n\n\u003c!-- START doctoc generated TOC please keep comment here to allow auto update --\u003e\n\u003c!-- DON'T EDIT THIS SECTION, INSTEAD RE-RUN doctoc TO UPDATE --\u003e\n\n- [Requirements](#requirements)\n  - [Ruby and Rails](#ruby-and-rails)\n  - [Image Processor](#image-processor)\n  - [`file`](#file)\n- [Installation](#installation)\n- [Quick Start](#quick-start)\n  - [Models](#models)\n  - [Migrations](#migrations)\n  - [Edit and New Views](#edit-and-new-views)\n  - [Edit and New Views with Simple Form](#edit-and-new-views-with-simple-form)\n  - [Controller](#controller)\n  - [View Helpers](#view-helpers)\n  - [Checking a File Exists](#checking-a-file-exists)\n  - [Deleting an Attachment](#deleting-an-attachment)\n- [Usage](#usage)\n- [Validations](#validations)\n- [Internationalization (I18n)](#internationalization-i18n)\n- [Security Validations](#security-validations)\n- [Defaults](#defaults)\n- [Migrations](#migrations-1)\n  - [Add Attachment Column To A Table](#add-attachment-column-to-a-table)\n  - [Schema Definition](#schema-definition)\n  - [Vintage Syntax](#vintage-syntax)\n- [Storage](#storage)\n  - [Understanding Storage](#understanding-storage)\n- [IO Adapters](#io-adapters)\n- [Post Processing](#post-processing)\n- [Custom Attachment Processors](#custom-attachment-processors)\n- [Events](#events)\n- [URI Obfuscation](#uri-obfuscation)\n- [Checksum / Fingerprint](#checksum--fingerprint)\n- [File Preservation for Soft-Delete](#file-preservation-for-soft-delete)\n- [Dynamic Configuration](#dynamic-configuration)\n  - [Dynamic Styles:](#dynamic-styles)\n  - [Dynamic Processors:](#dynamic-processors)\n- [Logging](#logging)\n- [Deployment](#deployment)\n  - [Attachment Styles](#attachment-styles)\n- [Testing](#testing)\n- [Contributing](#contributing)\n- [License](#license)\n- [About thoughtbot](#about-thoughtbot)\n\n\u003c!-- END doctoc generated TOC please keep comment here to allow auto update --\u003e\n\nPaperclip is intended as an easy file attachment library for ActiveRecord. The\nintent behind it was to keep setup as easy as possible and to treat files as\nmuch like other attributes as possible. This means they aren't saved to their\nfinal locations on disk, nor are they deleted if set to nil, until\nActiveRecord::Base#save is called. It manages validations based on size and\npresence, if required. It can transform its assigned image into thumbnails if\nneeded, and the prerequisites are as simple as installing ImageMagick (which,\nfor most modern Unix-based systems, is as easy as installing the right\npackages). Attached files are saved to the filesystem and referenced in the\nbrowser by an easily understandable specification, which has sensible and\nuseful defaults.\n\nSee the documentation for `has_attached_file` in [`Paperclip::ClassMethods`](http://www.rubydoc.info/gems/paperclip/Paperclip/ClassMethods) for\nmore detailed options.\n\nThe complete [RDoc](http://www.rubydoc.info/gems/paperclip) is online.\n\n---\n\nRequirements\n------------\n\n### Ruby and Rails\n\nPaperclip now requires Ruby version **\u003e= 2.1** and Rails version **\u003e= 4.2**\n(only if you're going to use Paperclip with Ruby on Rails).\n\n### Image Processor\n\n[ImageMagick](http://www.imagemagick.org) must be installed and Paperclip must have access to it. To ensure\nthat it does, on your command line, run `which convert` (one of the ImageMagick\nutilities). This will give you the path where that utility is installed. For\nexample, it might return `/usr/local/bin/convert`.\n\nThen, in your environment config file, let Paperclip know to look there by adding that\ndirectory to its path.\n\nIn development mode, you might add this line to `config/environments/development.rb)`:\n\n```ruby\nPaperclip.options[:command_path] = \"/usr/local/bin/\"\n```\n\nIf you're on Mac OS X, you'll want to run the following with [Homebrew](http://www.brew.sh):\n\n    brew install imagemagick\n\nIf you are dealing with pdf uploads or running the test suite, you'll also need\nto install GhostScript. On Mac OS X, you can also install that using Homebrew:\n\n    brew install gs\n\nIf you are on Ubuntu (or any Debian base Linux distribution), you'll want to run\nthe following with apt-get:\n\n    sudo apt-get install imagemagick -y\n\n### `file`\n\nThe Unix [`file` command](https://en.wikipedia.org/wiki/File_(command)) is required for content-type checking.\nThis utility isn't available in Windows, but comes bundled with Ruby [Devkit](https://github.com/oneclick/rubyinstaller/wiki/Development-Kit),\nso Windows users must make sure that the devkit is installed and added to the system `PATH`.\n\n**Manual Installation**\n\nIf you're using Windows 7+ as a development environment, you may need to install the `file.exe` application manually. The `file spoofing` system in Paperclip 4+ relies on this; if you don't have it working, you'll receive `Validation failed: Upload file has an extension that does not match its contents.` errors.\n\nTo manually install, you should perform the following:\n\n\u003e **Download \u0026 install `file` from [this URL](http://gnuwin32.sourceforge.net/packages/file.htm)**\n\nTo test, you can use the image below:\n![untitled](https://cloud.githubusercontent.com/assets/1104431/4524452/a1f8cce4-4d44-11e4-872e-17adb96f79c9.png)\n\nNext, you need to integrate with your environment - preferably through the `PATH` variable, or by changing your `config/environments/development.rb` file\n\n**PATH**\n\n    1. Click \"Start\"\n    2. On \"Computer\", right-click and select \"Properties\"\n    3. In Properties, select \"Advanced System Settings\"\n    4. Click the \"Environment Variables\" button\n    5. Locate the \"PATH\" var - at the end, add the path to your newly installed `file.exe` (typically `C:\\Program Files (x86)\\GnuWin32\\bin`)\n    6. Restart any CMD shells you have open \u0026 see if it works\n\nOR\n\n**Environment**\n\n    1. Open `config/environments/development.rb`\n    2. Add the following line: `Paperclip.options[:command_path] = 'C:\\Program Files (x86)\\GnuWin32\\bin'`\n    3. Restart your Rails server\n\nEither of these methods will give your Rails setup access to the `file.exe` functionality, thus providing the ability to check the contents of a file (fixing the spoofing problem)\n\n---\n\nInstallation\n------------\n\nPaperclip is distributed as a gem, which is how it should be used in your app.\n\nInclude the gem in your Gemfile:\n\n```ruby\ngem \"paperclip\", \"~\u003e 6.0.0\"\n```\n\nOr, if you want to get the latest, you can get master from the main paperclip repository:\n\n```ruby\ngem \"paperclip\", git: \"git://github.com/thoughtbot/paperclip.git\"\n```\n\nIf you're trying to use features that don't seem to be in the latest released gem, but are\nmentioned in this README, then you probably need to specify the master branch if you want to\nuse them. This README is probably ahead of the latest released version if you're reading it\non GitHub.\n\nFor Non-Rails usage:\n\n```ruby\nclass ModuleName \u003c ActiveRecord::Base\n  include Paperclip::Glue\n  ...\nend\n```\n\n---\n\nQuick Start\n-----------\n\n### Models\n\n```ruby\nclass User \u003c ActiveRecord::Base\n  has_attached_file :avatar, styles: { medium: \"300x300\u003e\", thumb: \"100x100\u003e\" }, default_url: \"/images/:style/missing.png\"\n  validates_attachment_content_type :avatar, content_type: /\\Aimage\\/.*\\z/\nend\n```\n\n### Migrations\n\n\nAssuming you have a `users` table, add an `avatar` column to the `users` table:\n```ruby\nclass AddAvatarColumnsToUsers \u003c ActiveRecord::Migration\n  def up\n    add_attachment :users, :avatar\n  end\n\n  def down\n    remove_attachment :users, :avatar\n  end\nend\n```\n\n(Or you can use the Rails migration generator: `rails generate paperclip user avatar`)\n\n### Edit and New Views\nMake sure you have corresponding methods in your controller:\n```erb\n\u003c%= form_for @user, url: users_path, html: { multipart: true } do |form| %\u003e\n  \u003c%= form.file_field :avatar %\u003e\n  \u003c%= form.submit %\u003e\n\u003c% end %\u003e\n```\n\n### Edit and New Views with [Simple Form](https://github.com/plataformatec/simple_form)\n\n```erb\n\u003c%= simple_form_for @user, url: users_path do |form| %\u003e\n  \u003c%= form.input :avatar, as: :file %\u003e\n  \u003c%= form.submit %\u003e\n\u003c% end %\u003e\n```\n\n### Controller\n\n```ruby\ndef create\n  @user = User.create(user_params)\nend\n\nprivate\n\n# Use strong_parameters for attribute whitelisting\n# Be sure to update your create() and update() controller methods.\n\ndef user_params\n  params.require(:user).permit(:avatar)\nend\n```\n\n### View Helpers\nAdd these to the view where you want your images displayed:\n```erb\n\u003c%= image_tag @user.avatar.url %\u003e\n\u003c%= image_tag @user.avatar.url(:medium) %\u003e\n\u003c%= image_tag @user.avatar.url(:thumb) %\u003e\n```\n\n### Checking a File Exists\n\nThere are two methods for checking if a file exists:\n\n- `file?` and `present?` checks if the `_file_name` field is populated\n- `exists?` checks if the file exists (will perform a TCP connection if stored in the cloud)\n\nKeep this in mind if you are checking if files are present in a loop. The first\nversion is significantly more performant, but has different semantics.\n\n### Deleting an Attachment\n\nSet the attribute to `nil` and save.\n\n```ruby\n@user.avatar = nil\n@user.save\n```\n---\n\nUsage\n-----\n\nThe basics of Paperclip are quite simple: Declare that your model has an\nattachment with the `has_attached_file` method, and give it a name.\n\nPaperclip will wrap up to four attributes (all prefixed with that attachment's name,\nso you can have multiple attachments per model if you wish) and give them a\nfriendly front end. These attributes are:\n\n* `\u003cattachment\u003e_file_name`\n* `\u003cattachment\u003e_file_size`\n* `\u003cattachment\u003e_content_type`\n* `\u003cattachment\u003e_updated_at`\n\nBy default, only `\u003cattachment\u003e_file_name` is required for Paperclip to operate.\nYou'll need to add `\u003cattachment\u003e_content_type` in case you want to use content type\nvalidation.\n\nMore information about the options passed to `has_attached_file` is available in the\ndocumentation of [`Paperclip::ClassMethods`](http://www.rubydoc.info/gems/paperclip/Paperclip/ClassMethods).\n\nValidations\n-----------\n\nFor validations, Paperclip introduces several validators to validate your attachment:\n\n* `AttachmentContentTypeValidator`\n* `AttachmentPresenceValidator`\n* `AttachmentSizeValidator`\n\nExample Usage:\n\n```ruby\nvalidates :avatar, attachment_presence: true\nvalidates_with AttachmentPresenceValidator, attributes: :avatar\nvalidates_with AttachmentSizeValidator, attributes: :avatar, less_than: 1.megabytes\n\n```\n\nValidators can also be defined using the old helper style:\n\n* `validates_attachment_presence`\n* `validates_attachment_content_type`\n* `validates_attachment_size`\n\nExample Usage:\n\n```ruby\nvalidates_attachment_presence :avatar\n```\n\nLastly, you can also define multiple validations on a single attachment using `validates_attachment`:\n\n```ruby\nvalidates_attachment :avatar, presence: true,\n  content_type: \"image/jpeg\",\n  size: { in: 0..10.kilobytes }\n```\n\n_NOTE: Post-processing will not even **start** if the attachment is not valid\naccording to the validations. Your callbacks and processors will **only** be\ncalled with valid attachments._\n\n```ruby\nclass Message \u003c ActiveRecord::Base\n  has_attached_file :asset, styles: { thumb: \"100x100#\" }\n\n  before_post_process :skip_for_audio\n\n  def skip_for_audio\n    ! %w(audio/ogg application/ogg).include?(asset_content_type)\n  end\nend\n```\n\nIf you have other validations that depend on assignment order, the recommended\ncourse of action is to prevent the assignment of the attachment until\nafterwards, then assign manually:\n\n```ruby\nclass Book \u003c ActiveRecord::Base\n  has_attached_file :document, styles: { thumbnail: \"60x60#\" }\n  validates_attachment :document, content_type: \"application/pdf\"\n  validates_something_else # Other validations that conflict with Paperclip's\nend\n\nclass BooksController \u003c ApplicationController\n  def create\n    @book = Book.new(book_params)\n    @book.document = params[:book][:document]\n    @book.save\n    respond_with @book\n  end\n\n  private\n\n  def book_params\n    params.require(:book).permit(:title, :author)\n  end\nend\n```\n\n**A note on content_type validations and security**\n\nYou should ensure that you validate files to be only those MIME types you\nexplicitly want to support.  If you don't, you could be open to\n\u003ca href=\"https://www.owasp.org/index.php/Testing_for_Stored_Cross_site_scripting_(OWASP-DV-002)\"\u003eXSS attacks\u003c/a\u003e\nif a user uploads a file with a malicious HTML payload.\n\nIf you're only interested in images, restrict your allowed content_types to\nimage-y ones:\n\n```ruby\nvalidates_attachment :avatar,\n  content_type: [\"image/jpeg\", \"image/gif\", \"image/png\"]\n```\n\n`Paperclip::ContentTypeDetector` will attempt to match a file's extension to an\ninferred content_type, regardless of the actual contents of the file.\n\n---\n\nInternationalization (I18n)\n---------------------------\n\nFor using or adding locale files in different languages, check the project\nhttps://github.com/thoughtbot/paperclip-i18n.\n\nSecurity Validations\n====================\n\nThanks to a report from [Egor Homakov](http://homakov.blogspot.com/) we have\ntaken steps to prevent people from spoofing Content-Types and getting data\nyou weren't expecting onto your server.\n\nNOTE: Starting at version 4.0.0, all attachments are *required* to include a\ncontent_type validation, a file_name validation, or to explicitly state that\nthey're not going to have either. *Paperclip will raise an error* if you do not\ndo this.\n\n```ruby\nclass ActiveRecord::Base\n  has_attached_file :avatar\n  # Validate content type\n  validates_attachment_content_type :avatar, content_type: /\\Aimage/\n  # Validate filename\n  validates_attachment_file_name :avatar, matches: [/png\\z/, /jpe?g\\z/]\n  # Explicitly do not validate\n  do_not_validate_attachment_file_type :avatar\nend\n```\n\nThis keeps Paperclip secure-by-default, and will prevent people trying to mess\nwith your filesystem.\n\nNOTE: Also starting at version 4.0.0, Paperclip has another validation that\ncannot be turned off. This validation will prevent content type spoofing. That\nis, uploading a PHP document (for example) as part of the EXIF tags of a\nwell-formed JPEG. This check is limited to the media type (the first part of the\nMIME type, so, 'text' in `text/plain`). This will prevent HTML documents from\nbeing uploaded as JPEGs, but will not prevent GIFs from being uploaded with a\n`.jpg` extension. This validation will only add validation errors to the form. It\nwill not cause errors to be raised.\n\nThis can sometimes cause false validation errors in applications that use custom\nfile extensions. In these cases you may wish to add your custom extension to the\nlist of content type mappings by creating `config/initializers/paperclip.rb`:\n\n```ruby\n# Allow \".foo\" as an extension for files with the MIME type \"text/plain\".\nPaperclip.options[:content_type_mappings] = {\n  foo: %w(text/plain)\n}\n```\n\n---\n\nDefaults\n--------\nGlobal defaults for all your Paperclip attachments can be defined by changing the Paperclip::Attachment.default_options Hash. This can be useful for setting your default storage settings per example so you won't have to define them in every `has_attached_file` definition.\n\nIf you're using Rails, you can define a Hash with default options in `config/application.rb` or in any of the `config/environments/*.rb` files on config.paperclip_defaults. These will get merged into `Paperclip::Attachment.default_options` as your Rails app boots. An example:\n\n```ruby\nmodule YourApp\n  class Application \u003c Rails::Application\n    # Other code...\n\n    config.paperclip_defaults = { storage: :fog, fog_credentials: { provider: \"Local\", local_root: \"#{Rails.root}/public\"}, fog_directory: \"\", fog_host: \"localhost\"}\n  end\nend\n```\n\nAnother option is to directly modify the `Paperclip::Attachment.default_options` Hash - this method works for non-Rails applications or is an option if you prefer to place the Paperclip default settings in an initializer.\n\nAn example Rails initializer would look something like this:\n\n```ruby\nPaperclip::Attachment.default_options[:storage] = :fog\nPaperclip::Attachment.default_options[:fog_credentials] = { provider: \"Local\", local_root: \"#{Rails.root}/public\"}\nPaperclip::Attachment.default_options[:fog_directory] = \"\"\nPaperclip::Attachment.default_options[:fog_host] = \"http://localhost:3000\"\n```\n---\n\nMigrations\n----------\n\nPaperclip defines several migration methods which can be used to create the necessary columns in your\nmodel. There are two types of helper methods to aid in this, as follows:\n\n### Add Attachment Column To A Table\n\nThe `attachment` helper can be used when creating a table:\n\n```ruby\nclass CreateUsersWithAttachments \u003c ActiveRecord::Migration\n  def up\n    create_table :users do |t|\n      t.attachment :avatar\n    end\n  end\n\n  # This is assuming you are only using the users table for Paperclip attachment. Drop with care!\n  def down\n    drop_table :users\n  end\nend\n```\n\nYou can also use the `change` method, instead of the `up`/`down` combination above, as shown below:\n\n```ruby\nclass CreateUsersWithAttachments \u003c ActiveRecord::Migration\n  def change\n    create_table :users do |t|\n      t.attachment :avatar\n    end\n  end\nend\n```\n\n### Schema Definition\n\nAlternatively, the `add_attachment` and `remove_attachment` methods can be used to add new Paperclip columns to an existing table:\n\n```ruby\nclass AddAttachmentColumnsToUsers \u003c ActiveRecord::Migration\n  def up\n    add_attachment :users, :avatar\n  end\n\n  def down\n    remove_attachment :users, :avatar\n  end\nend\n```\n\nOr you can do this with the `change` method:\n\n```ruby\nclass AddAttachmentColumnsToUsers \u003c ActiveRecord::Migration\n  def change\n    add_attachment :users, :avatar\n  end\nend\n```\n\n### Vintage Syntax\n\nVintage syntax (such as `t.has_attached_file` and `drop_attached_file`) is still supported in\nPaperclip 3.x, but you're advised to update those migration files to use this new syntax.\n\n---\n\nStorage\n-------\n\nPaperclip ships with 3 storage adapters:\n\n* File Storage\n* S3 Storage (via `aws-sdk-s3`)\n* Fog Storage\n\nIf you would like to use Paperclip with another storage, you can install these\ngems along side with Paperclip:\n\n* [paperclip-azure](https://github.com/supportify/paperclip-azure)\n* [paperclip-azure-storage](https://github.com/gmontard/paperclip-azure-storage)\n* [paperclip-dropbox](https://github.com/janko-m/paperclip-dropbox)\n\n### Understanding Storage\n\nThe files that are assigned as attachments are, by default, placed in the\ndirectory specified by the `:path` option to `has_attached_file`. By default, this\nlocation is `:rails_root/public/system/:class/:attachment/:id_partition/:style/:filename`.\nThis location was chosen because, on standard Capistrano deployments, the\n`public/system` directory can be symlinked to the app's shared directory, meaning it\nsurvives between deployments. For example, using that `:path`, you may have a\nfile at\n\n    /data/myapp/releases/20081229172410/public/system/users/avatar/000/000/013/small/my_pic.png\n\n_**NOTE**: This is a change from previous versions of Paperclip, but is overall a\nsafer choice for the default file store._\n\nYou may also choose to store your files using Amazon's S3 service. To do so, include\nthe `aws-sdk-s3` gem in your Gemfile:\n\n```ruby\ngem 'aws-sdk-s3'\n```\n\nAnd then you can specify using S3 from `has_attached_file`.\nYou can find more information about configuring and using S3 storage in\n[the `Paperclip::Storage::S3` documentation](http://www.rubydoc.info/gems/paperclip/Paperclip/Storage/S3).\n\nFiles on the local filesystem (and in the Rails app's public directory) will be\navailable to the internet at large. If you require access control, it's\npossible to place your files in a different location. You will need to change\nboth the `:path` and `:url` options in order to make sure the files are unavailable\nto the public. Both `:path` and `:url` allow the same set of interpolated\nvariables.\n\n---\n\nIO Adapters\n-----------\n\nWhen a file is uploaded or attached, it can be in one of a few different input\nforms, from Rails' UploadedFile object to a StringIO to a Tempfile or even a\nsimple String that is a URL that points to an image.\n\nPaperclip will accept, by default, many of these sources. It also is capable of\nhandling even more with a little configuration. The IO Adapters that handle\nimages from non-local sources are not enabled by default. They can be enabled by\nadding a line similar to the following into `config/initializers/paperclip.rb`:\n\n```ruby\nPaperclip::DataUriAdapter.register\n```\n\nIt's best to only enable a remote-loading adapter if you need it. Otherwise\nthere's a chance that someone can gain insight into your internal network\nstructure using it as a vector.\n\nThe following adapters are *not* loaded by default:\n\n* `Paperclip::UriAdapter` - which accepts a `URI` instance.\n* `Paperclip::HttpUrlProxyAdapter` - which accepts a `http` string.\n* `Paperclip::DataUriAdapter` - which accepts a Base64-encoded `data:` string.\n\n---\n\nPost Processing\n---------------\n\nPaperclip supports an extensible selection of post-processors. When you define\na set of styles for an attachment, by default it is expected that those\n\"styles\" are actually \"thumbnails.\" These are processed by\n`Paperclip::Thumbnail`.  For backward compatibility reasons you can pass either\na single geometry string, or an array containing a geometry and a format that\nthe file will be converted to, like so:\n\n```ruby\nhas_attached_file :avatar, styles: { thumb: [\"32x32#\", :png] }\n```\n\nThis will convert the \"thumb\" style to a 32x32 square in PNG format, regardless\nof what was uploaded. If the format is not specified, it is kept the same (e.g.\nJPGs will remain JPGs). `Paperclip::Thumbnail` uses ImageMagick to process\nimages; [ImageMagick's geometry documentation](http://www.imagemagick.org/script/command-line-processing.php#geometry)\nhas more information on the accepted style formats.\n\nFor more fine-grained control of the conversion process, `source_file_options` and `convert_options` can be used to pass flags and settings directly to ImageMagick's powerful Convert tool, [documented here](https://www.imagemagick.org/script/convert.php). For example:\n\n```ruby\nhas_attached_file :image, styles: { regular: ['800x800\u003e', :png]}, \n    source_file_options: { regular: \"-density 96 -depth 8 -quality 85\" },\n    convert_options: { regular: \"-posterize 3\"}\n```\n\nImageMagick supports a number of environment variables for controlling its resource limits. For example, you can enforce memory or execution time limits by setting the following variables in your application's process environment:\n\n* `MAGICK_MEMORY_LIMIT=128MiB`\n* `MAGICK_MAP_LIMIT=64MiB`\n* `MAGICK_TIME_LIMIT=30`\n\nFor a full list of variables and description, see [ImageMagick's resources documentation](http://www.imagemagick.org/script/resources.php).\n\n---\n\nCustom Attachment Processors\n-------\n\nYou can write your own custom attachment processors to carry out tasks like\nadding watermarks, compressing images, or encrypting files. Custom processors\nmust be defined within the `Paperclip` module, inherit from\n`Paperclip::Processor` (see [`lib/paperclip/processor.rb`](https://github.com/thoughtbot/paperclip/blob/master/lib/paperclip/processor.rb)),\nand implement a `make` method that returns a `File`. All files in your Rails\napp's `lib/paperclip` and `lib/paperclip_processors` directories will be\nautomatically loaded by Paperclip. Processors are specified using the\n`:processors` option to `has_attached_file`:\n\n```ruby\nhas_attached_file :scan, styles: { text: { quality: :better } },\n                         processors: [:ocr]\n```\n\nThis would load the hypothetical class `Paperclip::Ocr`, and pass it the\noptions hash `{ quality: :better }`, along with the uploaded file.\n\nMultiple processors can be specified, and they will be invoked in the order\nthey are defined in the `:processors` array. Each successive processor is given\nthe result from the previous processor. All processors receive the same\nparameters, which are defined in the `:styles` hash.  For example, assuming we\nhad this definition:\n\n```ruby\nhas_attached_file :scan, styles: { text: { quality: :better } },\n                         processors: [:rotator, :ocr]\n```\n\nBoth the `:rotator` processor and the `:ocr` processor would receive the\noptions `{ quality: :better }`. If a processor receives an option it doesn't\nrecognise, it's expected to ignore it.\n\n_NOTE: Because processors operate by turning the original attachment into the\nstyles, no processors will be run if there are no styles defined._\n\nIf you're interested in caching your thumbnail's width, height and size in the\ndatabase, take a look at the [paperclip-meta](https://github.com/teeparham/paperclip-meta)\ngem.\n\nAlso, if you're interested in generating the thumbnail on-the-fly, you might want\nto look into the [attachment_on_the_fly](https://github.com/drpentode/Attachment-on-the-Fly)\ngem.\n\nPaperclip's thumbnail generator (see [`lib/paperclip/thumbnail.rb`](lib/paperclip/thumbnail.rb))\nis implemented as a processor, and may be a good reference for writing your own\nprocessors.\n\n---\n\nEvents\n------\n\nBefore and after the Post Processing step, Paperclip calls back to the model\nwith a few callbacks, allowing the model to change or cancel the processing\nstep. The callbacks are `before_post_process` and `after_post_process` (which\nare called before and after the processing of each attachment), and the\nattachment-specific `before_\u003cattachment\u003e_post_process` and\n`after_\u003cattachment\u003e_post_process`. The callbacks are intended to be as close to\nnormal ActiveRecord callbacks as possible, so if you return false (specifically\n\\- returning nil is not the same) in a `before_filter`, the post processing step\nwill halt. Returning false in an `after_filter` will not halt anything, but you\ncan access the model and the attachment if necessary.\n\n_NOTE: Post processing will not even **start** if the attachment is not valid\naccording to the validations. Your callbacks and processors will **only** be\ncalled with valid attachments._\n\n```ruby\nclass Message \u003c ActiveRecord::Base\n  has_attached_file :asset, styles: { thumb: \"100x100#\" }\n\n  before_post_process :skip_for_audio\n\n  def skip_for_audio\n    ! %w(audio/ogg application/ogg).include?(asset_content_type)\n  end\nend\n```\n\n---\n\nURI Obfuscation\n---------------\n\nPaperclip has an interpolation called `:hash` for obfuscating filenames of\npublicly-available files.\n\nExample Usage:\n\n```ruby\nhas_attached_file :avatar, {\n    url: \"/system/:hash.:extension\",\n    hash_secret: \"longSecretString\"\n}\n```\n\n\nThe `:hash` interpolation will be replaced with a unique hash made up of whatever\nis specified in `:hash_data`. The default value for `:hash_data` is `\":class/:attachment/:id/:style/:updated_at\"`.\n\n`:hash_secret` is required - an exception will be raised if `:hash` is used without `:hash_secret` present.\n\nFor more on this feature, read [the author's own explanation](https://github.com/thoughtbot/paperclip/pull/416)\n\nChecksum / Fingerprint\n-------\n\nA checksum of the original file assigned will be placed in the model if it\nhas an attribute named fingerprint.  Following the user model migration example\nabove, the migration would look like the following:\n\n```ruby\nclass AddAvatarFingerprintColumnToUser \u003c ActiveRecord::Migration\n  def up\n    add_column :users, :avatar_fingerprint, :string\n  end\n\n  def down\n    remove_column :users, :avatar_fingerprint\n  end\nend\n```\n\nThe algorithm can be specified using a configuration option; it defaults to MD5\nfor backwards compatibility with Paperclip 5 and earlier.\n\n```ruby\nhas_attached_file :some_attachment, adapter_options: { hash_digest: Digest::SHA256 }\n```\n\nRun `CLASS=User ATTACHMENT=avatar rake paperclip:refresh:fingerprints` after\nchanging the digest on existing attachments to update the fingerprints in the\ndatabase.\n\nFile Preservation for Soft-Delete\n-------\n\nAn option is available to preserve attachments in order to play nicely with soft-deleted models. (acts_as_paranoid, paranoia, etc.)\n\n```ruby\nhas_attached_file :some_attachment, {\n    preserve_files: true,\n}\n```\n\nThis will prevent ```some_attachment``` from being wiped out when the model gets destroyed, so it will still exist when the object is restored later.\n\n---\n\nDynamic Configuration\n---------------------\n\nCallable objects (lambdas, Procs) can be used in a number of places for dynamic\nconfiguration throughout Paperclip.  This strategy exists in a number of\ncomponents of the library but is most significant in the possibilities for\nallowing custom styles and processors to be applied for specific model\ninstances, rather than applying defined styles and processors across all\ninstances.\n\n### Dynamic Styles:\n\nImagine a user model that had different styles based on the role of the user.\nPerhaps some users are bosses (e.g. a User model instance responds to `#boss?`)\nand merit a bigger avatar thumbnail than regular users. The configuration to\ndetermine what style parameters are to be used based on the user role might\nlook as follows where a boss will receive a `300x300` thumbnail otherwise a\n`100x100` thumbnail will be created.\n\n```ruby\nclass User \u003c ActiveRecord::Base\n  has_attached_file :avatar, styles: lambda { |attachment| { thumb: (attachment.instance.boss? ? \"300x300\u003e\" : \"100x100\u003e\") } }\nend\n```\n\n### Dynamic Processors:\n\nAnother contrived example is a user model that is aware of which file processors\nshould be applied to it (beyond the implied `thumbnail` processor invoked when\n`:styles` are defined). Perhaps we have a watermark processor available and it is\nonly used on the avatars of certain models.  The configuration for this might be\nwhere the instance is queried for which processors should be applied to it.\nPresumably some users might return `[:thumbnail, :watermark]` for its\nprocessors, where a defined `watermark` processor is invoked after the\n`thumbnail` processor already defined by Paperclip.\n\n```ruby\nclass User \u003c ActiveRecord::Base\n  has_attached_file :avatar, processors: lambda { |instance| instance.processors }\n  attr_accessor :processors\nend\n```\n\n---\n\nLogging\n----------\n\nBy default, Paperclip outputs logging according to your logger level. If you want to disable logging (e.g. during testing) add this into your environment's configuration:\n```ruby\nYour::Application.configure do\n...\n  Paperclip.options[:log] = false\n...\nend\n```\n\nMore information in the [rdocs](http://www.rubydoc.info/github/thoughtbot/paperclip/Paperclip.options)\n\n---\n\nDeployment\n----------\n\nTo make Capistrano symlink the `public/system` directory so that attachments\nsurvive new deployments, set the `linked_dirs` option in your `config/deploy.rb`\nfile:\n\n```ruby\nset :linked_dirs, fetch(:linked_dirs, []).push('public/system')\n```\n\n### Attachment Styles\n\nPaperclip is aware of new attachment styles you have added in previous deploys. The only thing you should do after each deployment is to call\n`rake paperclip:refresh:missing_styles`.  It will store current attachment styles in `RAILS_ROOT/public/system/paperclip_attachments.yml`\nby default. You can change it by:\n\n```ruby\nPaperclip.registered_attachments_styles_path = '/tmp/config/paperclip_attachments.yml'\n```\n\nHere is an example for Capistrano:\n\n```ruby\nnamespace :paperclip do\n  desc \"build missing paperclip styles\"\n  task :build_missing_styles do\n    on roles(:app) do\n      within release_path do\n        with rails_env: fetch(:rails_env) do\n          execute :rake, \"paperclip:refresh:missing_styles\"\n        end\n      end\n    end\n  end\nend\n\nafter(\"deploy:compile_assets\", \"paperclip:build_missing_styles\")\n```\n\nNow you don't have to remember to refresh thumbnails in production every time you add a new style.\nUnfortunately, it does not work with dynamic styles - it just ignores them.\n\nIf you already have a working app and don't want `rake paperclip:refresh:missing_styles` to refresh old pictures, you need to tell\nPaperclip about existing styles. Simply create a `paperclip_attachments.yml` file by hand. For example:\n\n```ruby\nclass User \u003c ActiveRecord::Base\n  has_attached_file :avatar, styles: { thumb: 'x100', croppable: '600x600\u003e', big: '1000x1000\u003e' }\nend\n\nclass Book \u003c ActiveRecord::Base\n  has_attached_file :cover, styles: { small: 'x100', large: '1000x1000\u003e' }\n  has_attached_file :sample, styles: { thumb: 'x100' }\nend\n```\n\nThen in `RAILS_ROOT/public/system/paperclip_attachments.yml`:\n\n```yml\n---\n:User:\n  :avatar:\n  - :thumb\n  - :croppable\n  - :big\n:Book:\n  :cover:\n  - :small\n  - :large\n  :sample:\n  - :thumb\n```\n\n---\n\nTesting\n-------\n\nPaperclip provides rspec-compatible matchers for testing attachments. See the\ndocumentation on [Paperclip::Shoulda::Matchers](http://www.rubydoc.info/gems/paperclip/Paperclip/Shoulda/Matchers)\nfor more information.\n\n**Parallel Tests**\n\nBecause of the default `path` for Paperclip storage, if you try to run tests in\nparallel, you may find that files get overwritten because the same path is being\ncalculated for them in each test process. While this fix works for\nparallel_tests, a similar concept should be used for any other mechanism for\nrunning tests concurrently.\n\n```ruby\nif ENV['PARALLEL_TEST_GROUPS']\n  Paperclip::Attachment.default_options[:path] = \":rails_root/public/system/:rails_env/#{ENV['TEST_ENV_NUMBER'].to_i}/:class/:attachment/:id_partition/:filename\"\nelse\n  Paperclip::Attachment.default_options[:path] = \":rails_root/public/system/:rails_env/:class/:attachment/:id_partition/:filename\"\nend\n```\n\nThe important part here being the inclusion of `ENV['TEST_ENV_NUMBER']`, or a\nsimilar mechanism for whichever parallel testing library you use.\n\n**Integration Tests**\n\nUsing integration tests with FactoryBot may save multiple copies of\nyour test files within the app. To avoid this, specify a custom path in\nthe `config/environments/test.rb` like so:\n\n```ruby\nPaperclip::Attachment.default_options[:path] = \"#{Rails.root}/spec/test_files/:class/:id_partition/:style.:extension\"\n```\n\nThen, make sure to delete that directory after the test suite runs by adding\nthis to `spec_helper.rb`.\n\n```ruby\nconfig.after(:suite) do\n  FileUtils.rm_rf(Dir[\"#{Rails.root}/spec/test_files/\"])\nend\n```\n\n**Example of test configuration with Factory Bot**\n\n\n```ruby\nFactoryBot.define do\n  factory :user do\n    avatar { File.new(\"#{Rails.root}/spec/support/fixtures/image.jpg\") }\n  end\nend\n```\n---\n\nContributing\n------------\n\nIf you'd like to contribute a feature or bugfix: Thanks! To make sure your\nfix/feature has a high chance of being included, please read the following\nguidelines:\n\n1. Post a [pull request](https://github.com/thoughtbot/paperclip/compare/).\n2. Make sure there are tests! We will not accept any patch that is not tested.\n   It's a rare time when explicit tests aren't needed. If you have questions\n   about writing tests for paperclip, please open a\n   [GitHub issue](https://github.com/thoughtbot/paperclip/issues/new).\n\nPlease see [`CONTRIBUTING.md`](./CONTRIBUTING.md) for more details on contributing and running test.\n\nThank you to all [the contributors](https://github.com/thoughtbot/paperclip/graphs/contributors)!\n\nLicense\n-------\n\nPaperclip is Copyright © 2008-2017 thoughtbot, inc. It is free software, and may be\nredistributed under the terms specified in the MIT-LICENSE file.\n\nAbout thoughtbot\n----------------\n\n![thoughtbot](http://presskit.thoughtbot.com/images/thoughtbot-logo-for-readmes.svg)\n\nPaperclip is maintained and funded by thoughtbot.\nThe names and logos for thoughtbot are trademarks of thoughtbot, inc.\n\nWe love open source software!\nSee [our other projects][community] or\n[hire us][hire] to design, develop, and grow your product.\n\n[community]: https://thoughtbot.com/community?utm_source=github\n[hire]: https://thoughtbot.com?utm_source=github\n","funding_links":[],"categories":["File Uploading","Rails Plugins","Ruby","File Upload","others","文件上传","Gems"],"sub_categories":["Omniauth","Rails File Uploads","ActiveRecord"],"project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fthoughtbot%2Fpaperclip","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fthoughtbot%2Fpaperclip","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fthoughtbot%2Fpaperclip/lists"}