{"id":26942441,"url":"https://github.com/wearepush/paperclip","last_synced_at":"2025-09-13T12:41:02.384Z","repository":{"id":96017382,"uuid":"595221365","full_name":"wearepush/paperclip","owner":"wearepush","description":null,"archived":false,"fork":false,"pushed_at":"2023-01-30T17:02:06.000Z","size":260,"stargazers_count":0,"open_issues_count":0,"forks_count":0,"subscribers_count":2,"default_branch":"main","last_synced_at":"2025-04-02T16:52:21.425Z","etag":null,"topics":[],"latest_commit_sha":null,"homepage":null,"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/wearepush.png","metadata":{"files":{"readme":"README.md","changelog":"NEWS","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,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2023-01-30T16:39:43.000Z","updated_at":"2023-01-30T16:48:07.000Z","dependencies_parsed_at":"2023-07-09T12:48:56.885Z","dependency_job_id":null,"html_url":"https://github.com/wearepush/paperclip","commit_stats":null,"previous_names":[],"tags_count":0,"template":false,"template_full_name":null,"purl":"pkg:github/wearepush/paperclip","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/wearepush%2Fpaperclip","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/wearepush%2Fpaperclip/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/wearepush%2Fpaperclip/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/wearepush%2Fpaperclip/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/wearepush","download_url":"https://codeload.github.com/wearepush/paperclip/tar.gz/refs/heads/main","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/wearepush%2Fpaperclip/sbom","scorecard":null,"host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":274961860,"owners_count":25381893,"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","status":"online","status_checked_at":"2025-09-13T02:00:10.085Z","response_time":70,"last_error":null,"robots_txt_status":"success","robots_txt_updated_at":"2025-07-24T06:49:26.215Z","robots_txt_url":"https://github.com/robots.txt","online":true,"can_crawl_api":true,"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":"2025-04-02T16:49:05.820Z","updated_at":"2025-09-13T12:41:02.367Z","avatar_url":"https://github.com/wearepush.png","language":"Ruby","funding_links":[],"categories":[],"sub_categories":[],"readme":"Paperclip\n=========\n\n[![Build Status](https://secure.travis-ci.org/thoughtbot/paperclip.svg?branch=master)](http://travis-ci.org/thoughtbot/paperclip) [![Dependency Status](https://gemnasium.com/thoughtbot/paperclip.svg?travis)](https://gemnasium.com/thoughtbot/paperclip) [![Code Climate](https://codeclimate.com/github/thoughtbot/paperclip.svg)](https://codeclimate.com/github/thoughtbot/paperclip) [![Inline docs](http://inch-ci.org/github/thoughtbot/paperclip.svg)](http://inch-ci.org/github/thoughtbot/paperclip) [![Security](https://hakiri.io/github/thoughtbot/paperclip/master.svg)](https://hakiri.io/github/thoughtbot/paperclip/master)\n\n- [Requirements](#requirements)\n  - [Ruby on 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  - [Show View](#show-view)\n  - [Deleting an Attachment](#deleting-an-attachment)\n- [Usage](#usage)\n- [Validations](#validations)\n- [Security Validations](#security-validations)\n- [Defaults](#defaults)\n- [Migrations](#migrations-1)\n  - [Table Definition](#table-definition)\n  - [Schema Definition](#schema-definition)\n  - [Vintage Syntax](#vintage-syntax)\n- [Storage](#storage)\n  - [Understanding Storage](#understanding-storage)\n- [Post Processing](#post-processing)\n- [Events](#events)\n- [URI Obfuscation](#uri-obfuscation)\n  - [MD5 Checksum / Fingerprint](#md5-checksum--fingerprint)\n  - [File Preservation for Soft-Delete](#file-preservation-for-soft-delete)\n- [Custom Attachment Processors](#custom-attachment-processors)\n- [Dynamic Configuration](#dynamic-configuration)\n  - [Dynamic Styles](#dynamic-styles)\n  - [Dynamic Processors](#dynamic-processors)\n- [Logging](#logging)\n- [Deployment](#deployment)\n- [Testing](#testing)\n- [Contributing](#contributing)\n- [License](#license)\n- [About thoughtbot](#about-thoughtbot)\n\nPaperclip is intended as an easy file attachment library for Active Record. 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://rubydoc.info/gems/paperclip/Paperclip/ClassMethods) for\nmore detailed options.\n\nThe complete [RDoc](http://rdoc.info/gems/paperclip) is online.\n\n---\n\nRequirements\n------------\n\n### Ruby and Rails\n\nPaperclip now requires Ruby version **\u003e= 2.0.0** and Rails version **3.2, \u003e= 4.1** (Only if you're going to use Paperclip with Ruby on Rails.)\n\nIf you're still on Ruby 1.8.7 or Ruby on Rails 2.3.x, you can still use Paperclip 2.7.x with your project. Also, everything in this README might not apply to your version of Paperclip, and you should read [the README for version 2.7](http://rubydoc.info/gems/paperclip/2.7.0) instead.\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:\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're on Ubuntu, you'll want to run the following with apt-get:\n\n    sudo apt-get install imagemagick -y\n\nIf you're on Ubuntu (or any Debian base Linux distribution), you'll want to run the following with apt-get:\n\n    sudo apt-get install imagemagick -y\n\n### `file`\n\nThe Unix [`file` command](http://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 4.3\"\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 =\u003e \"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**Rails 3**\n\n```ruby\nclass User \u003c ActiveRecord::Base\n  attr_accessible :avatar\n  has_attached_file :avatar, :styles =\u003e { :medium =\u003e \"300x300\u003e\", :thumb =\u003e \"100x100\u003e\" }, :default_url =\u003e \"/images/:style/missing.png\"\n  validates_attachment_content_type :avatar, :content_type =\u003e /\\Aimage\\/.*\\Z/\nend\n```\n\n**Rails 4**\n\n```ruby\nclass User \u003c ActiveRecord::Base\n  has_attached_file :avatar, :styles =\u003e { :medium =\u003e \"300x300\u003e\", :thumb =\u003e \"100x100\u003e\" }, :default_url =\u003e \"/images/:style/missing.png\"\n  validates_attachment_content_type :avatar, :content_type =\u003e /\\Aimage\\/.*\\Z/\nend\n```\n\n### Migrations\n\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\n\n```erb\n\u003c%= form_for @user, :url =\u003e users_path, :html =\u003e { :multipart =\u003e true } do |form| %\u003e\n  \u003c%= form.file_field :avatar %\u003e\n\u003c% end %\u003e\n```\n\n### Edit and New Views with Simple Form\n```erb\n\u003c%= simple_form_for @user, url: users_path do |form| %\u003e\n  \u003c%= form.input :avatar, as: :file %\u003e\n\u003c% end %\u003e\n```\n\n### Controller\n\n**Rails 3**\n\n```ruby\ndef create\n  @user = User.create( params[:user] )\nend\n```\n\n**Rails 4**\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### Show View\n\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### 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://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 =\u003e true\nvalidates_with AttachmentPresenceValidator, :attributes =\u003e :avatar\nvalidates_with AttachmentSizeValidator, :attributes =\u003e :avatar, :less_than =\u003e 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 =\u003e true,\n  :content_type =\u003e { :content_type =\u003e \"image/jpeg\" },\n  :size =\u003e { :in =\u003e 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: { 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 =\u003e { :content_type =\u003e [\"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\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 =\u003e /\\Aimage/\n  # Validate filename\n  validates_attachment_file_name :avatar, :matches =\u003e [/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 file extensions allowed for your MIME type configured by the `mime-types`\ngem:\n\n```ruby\n# Allow \".foo\" as an extension for files with the MIME type \"text/plain\".\ntext_plain = MIME::Types[\"text/plain\"].first\ntext_plain.extensions \u003c\u003c \"foo\"\nMIME::Types.index_extensions text_plain\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 =\u003e :fog, :fog_credentials =\u003e {:provider =\u003e \"Local\", :local_root =\u003e \"#{Rails.root}/public\"}, :fog_directory =\u003e \"\", :fog_host =\u003e \"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 =\u003e \"Local\", :local_root =\u003e \"#{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\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`)\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-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 is symlinked to the app's shared directory, meaning it\nwill survive 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` gem in your Gemfile:\n\n```ruby\ngem 'aws-sdk', '~\u003e 1.6'\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://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\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.\" However, you can do much more than just\nthumbnail images. By defining a subclass of Paperclip::Processor, you can\nperform any processing you want on the files that are attached. Any file in\nyour Rails app's `lib/paperclip` and `lib/paperclip_processors` directories is\nautomatically loaded by Paperclip, allowing you to easily define custom\nprocessors. You can specify a processor with the `:processors` option to\n`has_attached_file`:\n\n```ruby\nhas_attached_file :scan, :styles =\u003e { :text =\u003e { :quality =\u003e :better } },\n                         :processors =\u003e [:ocr]\n```\n\nThis would load the hypothetical class Paperclip::Ocr, which would have the\nhash \"{ :quality =\u003e :better }\" passed to it along with the uploaded file. For\nmore information about defining processors, see Paperclip::Processor.\n\nThe default processor is Paperclip::Thumbnail. For backwards compatibility\nreasons, you can pass a single geometry string or an array containing a\ngeometry and a format that the file will be converted to, like so:\n\n```ruby\nhas_attached_file :avatar, :styles =\u003e { :thumb =\u003e [\"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 (i.e.\nJPGs will remain JPGs). For more information on the accepted style formats, see\n[here](http://www.imagemagick.org/script/command-line-processing.php#geometry).\n\nMultiple processors can be specified, and they will be invoked in the order\nthey are defined in the `:processors` array. Each successive processor will\nbe given the result of the previous processor's execution. All processors will\nreceive the same parameters, which are defined in the `:styles` hash.\nFor example, assuming we had this definition:\n\n```ruby\nhas_attached_file :scan, :styles =\u003e { :text =\u003e { :quality =\u003e :better } },\n                         :processors =\u003e [:rotator, :ocr]\n```\n\nthen both the :rotator processor and the :ocr processor would receive the\noptions `{ :quality =\u003e :better }`. This parameter may not mean anything to one\nor more or the processors, and they are 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) gem.\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) gem.\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 =\u003e \"/system/:hash.:extension\",\n    :hash_secret =\u003e \"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\nMD5 Checksum / Fingerprint\n-------\n\nAn MD5 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\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 =\u003e \"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\nCustom Attachment Processors\n-------\n\nCustom attachment processors can be implemented and their only requirement is\nto inherit from `Paperclip::Processor` (see `lib/paperclip/processor.rb`).\nFor example, when `:styles` are specified for an image attachment, the\nthumbnail processor (see `lib/paperclip/thumbnail.rb`) is loaded without having\nto specify it as a `:processor` parameter to `has_attached_file`.  When any\nother processor is defined, it must be called out in the `:processors`\nparameter if it is to be applied to the attachment.  The thumbnail processor\nuses the ImageMagick `convert` command to do the work of resizing image\nthumbnails.  It would be easy to create a custom processor that watermarks\nan image using ImageMagick's `composite` command.  Following the\nimplementation pattern of the thumbnail processor would be a way to implement a\nwatermark processor.  All kinds of attachment processors can be created;\na few utility examples would be compression and encryption processors.\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 =\u003e lambda { |attachment| { :thumb =\u003e (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 =\u003e 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 in to 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://rdoc.info/github/thoughtbot/paperclip/Paperclip.options)\n\n---\n\nDeployment\n----------\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 :deploy do\n  desc \"build missing paperclip styles\"\n  task :build_missing_paperclip_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\", \"deploy:build_missing_paperclip_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 =\u003e {:thumb =\u003e 'x100', :croppable =\u003e '600x600\u003e', :big =\u003e '1000x1000\u003e'}\nend\n\nclass Book \u003c ActiveRecord::Base\n  has_attached_file :cover, :styles =\u003e {:small =\u003e 'x100', :large =\u003e '1000x1000\u003e'}\n  has_attached_file :sample, :styles =\u003e {:thumb =\u003e '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://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 FactoryGirl 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\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` for more details on contributing and running test.\n\nThank you to all [the contributors](https://github.com/thoughtbot/paperclip/contributors)!\n\nLicense\n-------\n\nPaperclip is Copyright © 2008-2015 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](https://thoughtbot.com/logo.png)\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","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fwearepush%2Fpaperclip","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fwearepush%2Fpaperclip","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fwearepush%2Fpaperclip/lists"}