diff --git a/NEWS b/NEWS deleted file mode 100644 index 46cc8f163..000000000 --- a/NEWS +++ /dev/null @@ -1,515 +0,0 @@ -6.1.0 (2018-07-27): - -* BUGFIX: Don't double-encode URLs (Roderick Monje). -* BUGFIX: Only use the content_type when it exists (Jean-Philippe Doyle). -* STABILITY: Better handling of the content-disposition header. Now supports - file name that is either enclosed or not in double quotes and is case - insensitive as per RC6266 grammar (Hasan Kumar, Yves Riel). -* STABILITY: Change database column type of attachment file size from unsigned 4-byte - `integer` to unsigned 8-byte `bigint`. The former type limits attachment size - to just over 2GB, which can easily be exceeded by a large video file (Laurent - Arnoud, Alen Zamanyan). -* STABILITY: Better error message when thumbnail processing errors (Hayden Ball). -* STABILITY: Fix file linking issues around Windows (Akihiko Odaki). -* STABILITY: Files without an extension will now be checked for spoofing attempts - (George Walters II). -* STABILITY: Manually close Tempfiles when we are done with them (Erkki Eilonen). - -6.0.0 (2018-03-09): - -* Improvement: Depend only on `aws-sdk-s3` instead of `aws-sdk` (https://github.com/thoughtbot/paperclip/pull/2481) - -5.3.0 (2018-03-09): - -* Improvement: Use `FactoryBot` instead of `FactoryGirl` (https://github.com/thoughtbot/paperclip/pull/2501) -* Improvement: README updates (https://github.com/thoughtbot/paperclip/pull/2411, https://github.com/thoughtbot/paperclip/pull/2433, https://github.com/thoughtbot/paperclip/pull/2374, https://github.com/thoughtbot/paperclip/pull/2417, https://github.com/thoughtbot/paperclip/pull/2536) -* Improvement: Remove Ruby 2.4 deprecation warning (https://github.com/thoughtbot/paperclip/pull/2401) -* Improvement: Rails 5 migration compatibility (https://github.com/thoughtbot/paperclip/pull/2470) -* Improvement: Documentation around post processing (https://github.com/thoughtbot/paperclip/pull/2381) -* Improvement: S3 hostname example documentation (https://github.com/thoughtbot/paperclip/pull/2379) -* Bugfix: Allow paperclip to load in IRB (https://github.com/thoughtbot/paperclip/pull/2369) -* Bugfix: MIME type detection (https://github.com/thoughtbot/paperclip/issues/2527) -* Bugfix: Bad tempfile state after symlink failure (https://github.com/thoughtbot/paperclip/pull/2540) -* Bugfix: Rewind file after Fog bucket creation (https://github.com/thoughtbot/paperclip/pull/2572) -* Improvement: Use `Terrapin` instead of `Cocaine` (https://github.com/thoughtbot/paperclip/pull/2553) - -5.2.1 (2018-01-25): - -* Bugfix: Fix copying files on Windows. (#2532) - -5.2.0 (2018-01-23): - -* Security: Remove the automatic loading of URI adapters. Some of these - adapters can be specially crafted to expose your network topology. (#2435) -* Bugfix: The rake task no longer rescues `Exception`. (#2476) -* Bugfix: Handle malformed `Content-Disposition` headers (#2283) -* Bugfix: The `:only_process` option works when passed a lambda again. (#2289) -* Improvement: Added `:use_accelerate_endpoint` option when using S3 to enable - [Amazon S3 Transfer Acceleration](http://docs.aws.amazon.com/AmazonS3/latest/dev/transfer-acceleration.html) - (#2291) -* Improvement: Make the fingerprint digest configurable per attachment. The - default remains MD5. Making this configurable means it can change in a future - version because it is not considered secure anymore against intentional file - corruption. For more info, see https://en.wikipedia.org/wiki/MD5#Security - - You can change the digest used for an attachment by adding the - `:adapter_options` parameter to the `has_attached_file` options like this: - `has_attached_file :avatar, adapter_options: { hash_digest: Digest::SHA256 }` - - Use the rake task to regenerate fingerprints with the new digest for a given - class. Note that this does **not** check the file integrity using the old - fingerprint. Run the following command to regenerate fingerprints for all - User attachments: - `CLASS=User rake paperclip:refresh:fingerprints` - You can optionally limit the attachment that will be processed, e.g: - `CLASS=User ATTACHMENT=avatar rake paperclip:refresh:fingerprints` (#2229) -* Improvement: The new `frame_index` option on the thumbnail processor allows - you to select a specific frame from an animated upload to use as a thumbnail. - Initial support is for mkv, avi, MP4, mov, MPEG, and GIF. (#2155) -* Improvement: Instead of copying files, use hard links. This is an - optimization. (#2120) -* Improvement: S3 storage option `:s3_prefixes_in_alias`. (#2287) -* Improvement: Fog option `:fog_public` can be a lambda. (#2302) -* Improvement: One fewer warning on JRuby. (#2352) -* Ruby 2.4.0 compatibility (doesn't use Fixnum anymore) - -5.1.0 (2016-08-19): - -* Add default `content_type_detector` to `UploadedFileAdapter` (#2270) -* Default S3 protocol to empty string (#2038) -* Don't write original file if it wasn't reprocessed (#1993) -* Disallow trailing newlines in regular expressions (#2266) -* Support for readbyte in Paperclip attachments (#2034) -* (port from 4.3) Uri io adapter uses the content-disposition filename (#2250) -* General refactors and documentation improvements - -5.0.0 (2016-07-01): - -* Improvement: Add `read_timeout` configuration for URI Adapter download_content method. -* README adjustments for Ruby beginners (add links, elucidate model in Quick Start) -* Bugfix: Now it's possible to save images from URLs with special characters [#1932] -* Bugfix: Return false when file to copy is not present in cloud storage [#2173] -* Automatically close file while checking mime type [#2016] -* Add `read_timeout` option to `UriAdapter#download_content` method [#2232] -* Fix a nil error in content type validation matcher [#1910] -* Documentation improvements - -5.0.0.beta2 (2016-04-01): - -* Bugfix: Dynamic fog directory option is now respected -* Bugfix: Fixes cocaine duplicated paths [#2169] -* Removal of dead code (older versions of Rails and AWS SDK) -* README adjustments - -5.0.0.beta1 (2016-03-13): - -* Bug Fix: megabytes of mime-types info in logs when a spoofed media type is detected. -* Drop support to end-of-life'd ruby 2.0. -* Drop support for end-of-life'd Rails 3.2 and 4.1 -* Drop support for AWS v1 -* Remove tests for JRuby and Rubinius from Travis CI (they were failing) -* Improvement: Add `fog_options` configuration to send options to fog when - storing files. -* Extracted repository for locales only: https://github.com/thoughtbot/paperclip-i18n -* Bugfix: Original file could be unlinked during `post_process_style`, producing failures -* Bugfix for image magick scaling images up -* Memory consumption improvements -* `url` on a unpersisted record returns `default_url` rather than `nil` -* Improvement: aws-sdk v2 support - https://github.com/thoughtbot/paperclip/pull/1903 - - If your Gemfile contains aws-sdk (>= 2.0.0) and aws-sdk-v1, paperclip will use - aws-sdk v2. With aws-sdk v2, S3 storage requires you to set the s3_region. - s3_region may be nested in s3_credentials, and (if not nested in - s3_credentials) it may be a Proc. - -4.3 - -See patch versions in v4.3 NEWS: -https://github.com/thoughtbot/paperclip/blob/v4.3/NEWS - -4.3.0 (2015-06-18): - -* Improvement: Update aws-sdk and cucumber gem versions. -* Improvement: Add `length` alias for `size` method in AbstractAdapter. -* Improvement: Removed some cruft -* Improvement: deep_merge! Attachment definitions -* Improvement: Switch to mimemagic gem for content-type detection -* Improvement: Allows multiple content types for spoof detector -* Bug Fix: Don't assume we have Rails.env if we have Rails -* Performance: Decrease Memory footprint -* Ruby Versioning: Drop support for 1.9.3 (EOL'ed) -* Rails Versioning: Drop support for 4.0.0 (EOL'ed) - -4.2.4 (2015-06-05): - -* Rollback backwards incompatible change, allowing paperclip to run on - Ruby >= 1.9.2. - -4.2.3: - -* Fix dependency specifications (didn't work with Rails 4.1) -* Fix paperclip tests in CI - -4.2.2: - -* Security fix: Fix a potential security issue with spoofing - -4.2.1: - -* Improvement: Added `validate_media_type` options to allow/bypass spoof check -* Improvement: Added incremental backoff when AWS gives us a SlowDown error. -* Improvement: Stream downloads when usign aws-sdk. -* Improvement: Documentation fixes, includes Windows instructions. -* Improvement: Added pt-BR, zh-HK, zh-CN, zh-TW, and ja-JP locales. -* Improvement: Better escaping for characters in URLs -* Improvement: Honor `fog_credentials[:scheme]` -* Improvement: Also look for custom processors in lib/paperclip -* Improvement: id partitioning for string IDs works like integer id -* Improvement: Can pass options to DB adapters in migrations -* Improvement: Update expiring_url creation for later versions of fog -* Improvement: `path` can be a Proc in S3 attachments -* Test Fix: Improves speed and reliability of the specs -* Bug Fix: #original_filename= does not error when passed `nil` - -4.2.0: - -* Improvement: Converted test suite from test/unit to RSpec -* Improvement: Refactored Paperclip::Attachment#assign -* Improvement: Added Spanish and German locales -* Improvement: Required Validators accept validator subclasses -* Improvement: EXIF orientation checking can be turned off for performance -* Improvement: Documentation updates -* Improvement: Better #human_size method for AttachmentSizeValidators -* Bug Fix: Allow MIME-types with dots in them -* Improvement: Travis CI updates -* Improvement: Validators can take multiple messages -* Improvement: Per-style options for S3 storage -* Improvement: Allow `nil` geometry strings -* Improvement: Use `eager_load!` - -4.1.1: - -* Improvement: Add default translations for spoof validation -* Bug Fix: Don't check for spoofs if the file hasn't changed -* Bug Fix: Callback chain terminator is different in Rails 4.1, remove warnings -* Improvement: Fixed various Ruby warnings -* Bug Fix: Give bundler a hint, so it doesn't run forever on a fresh bundle -* Improvement: Documentation fixes -* Improvement: Allow travis-ci to finish-fast - - -4.1.0: - -* Improvement: Add :content_type_mappings to correct for missing spoof types -* Improvement: Credit Egor Homakov with discovering the content_type spoof bug -* Improvement: Memoize calls to identify in the thumbnail processor -* Improvement: Make MIME type optional for Data URIs. -* Improvement: Add default format for styles - -4.0.0: - -* Security: Attachments are checked to make sure they're not pulling a fast one. -* Security: It is now *enforced* that every attachment has a file/mime validation. -* Bug Fix: Removed a call to IOAdapter#close that was causing issues. -* Improvement: Added bullets to the 3.5.3 list of changes. Very important. -* Improvement: Updated the copyright to 2014 - -3.5.3: - -* Improvement: After three long, hard years... we know how to upgrade -* Bug Fix: #expiring_url returns 'missing' urls if nothing is attached -* Improvement: Lots of documentation fixes -* Improvement: Lots of fixes for Ruby warnings -* Improvement: Test the most appropriate Ruby/Rails comobinations on Travis -* Improvement: Delegate more IO methods through IOAdapters -* Improvement: Remove Rails 4 deprecations -* Improvement: Both S3's and Fog's #expiring_url can take a Time or Int -* Bug Fix: Both S3's and Fog's expiring_url respect style when missing the file -* Bug Fix: Timefiles will have a reasonable-length name. They're all MD5 hashes now -* Bug Fix: Don't delete files off S3 when reprocessing due to AWS inconsistencies -* Bug Fix: "swallow_stream" isn't thread dafe. Use :swallow_stderr -* Improvement: Regexps use \A and \Z instead of ^ and $ -* Improvement: :s3_credentials can take a lambda as an argument -* Improvement: Search up the class heirarchy for attachments -* Improvement: deep_merge options instead of regular merge -* Bug Fix: Prevent file deletion on transaction rollback -* Test Improvement: Ensure more files are properly closed during tests -* Test Bug Fix: Return the gemfile's syntax to normal - -3.5.2: - -* Security: Force cocaine to at least 0.5.3 to include a security fix -* Improvement: Fixed some README exmaples -* Feature: Added HTTP URL Proxy Adapter, can assign string URLs as attachments -* Improvement: Put validation errors on the base attribute and the sub-attribute - -3.5.1: - -* Bug Fix: Returned the class-level `attachment_definitions` method for compatability. -* Improvement: Ensured compatability with Rails 4 -* Improvement: Added Rails 4 to the Appraisals -* Bug Fix: #1296, where validations were generating errors -* Improvement: Specify MIT license in the gemspec - -3.5.0: - -* Feature: Handle Base64-encoded data URIs as uploads -* Feature: Add a FilenameCleaner class to allow custom filename sanitation -* Improvement: Satisfied Mocha deprecation warnings -* Bug Fix: Allow empty string to be submitted and ignored, as some forms do this -* Improvement: Make #expiring_url behavior consistent with #url -* Bug Fix: "Validate" attachments without invoking AR's validations -* Improvement: Various refactorings for a cleaner codebase -* Improvement: Be agnostic, use ActiveModel when appropriate -* Improvement: Add validation errors to the base attachment attribute -* Improvement: Handle errors in rake tasks -* Improvement: Largely refactor has_attached_file into a new class -* Improvement: Added Ruby 2.0.0 as a supported platform and removed 1.8.7 -* Improvement: Fixed some incompatabilities in the test suite - -3.4.2: - -* Improvement: Use https for Gemfile urls -* Improvement: Updated and more correct documentation -* Improvement: Use the -optimize flag on animated GIFs -* Improvement: Remove the Gemfile.lock -* Improvement: Add #expiring_url as an alias for #url until the storage defines it -* Improvement: Remove path clash checking, as it's unnecessary -* Bug Fix: Do not rely on checking version numbers for aws-sdk - -3.4.1: - -* Improvement: Various documentation fixes and improvements -* Bug Fix: Clearing an attachment with `preserve_files` on should still clear the attachment -* Bug Fix: Instances are #changed? when a new file is assigned -* Bug Fix: Correctly deal with S3 styles when using a lambda -* Improvement: Accept and pass :credential_provider option to AWS-SDK -* Bug Fix: Sanitize original_filename more correctly in IO Adapters -* Improvement: s3_host_name can be a lambda -* Improvement: Cache some interpolations for speed -* Improvement: Update to latest cocaine -* Improvement: Update copyrights, various typos - -3.4.0: - -* Bug Fix: Allow UploadedFileAdapter to force the use of `file` -* Bug Fix: Close the file handle when dealing with URIs -* Bug Fix: Ensure files are closed for writing when we're done. -* Bug Fix: Fixed 'type' being nil on Windows 7 error. -* Bug Fix: Fixed nil access when no s3 headers are defined -* Bug Fix: Fixes auto_orientation -* Bug Fix: Prevent a missing method error when switching from aws_sdk to fog -* Bug Fix: Properly fail to process invalid attachments -* Bug Fix: Server-side encryption is specified correctly -* Bug Fix: fog_public returned to true by default -* Bug Fix: Check attachment paths for duplicates, not URLs -* Feature: Add Attachment#blank? -* Feature: Add support for blacklisting certain content_types -* Feature: Add support for style-specific s3 headers and meta data -* Feature: Allow only_process to be a lambda -* Feature: Allow setting of escape url as a default option -* Feature: Create :override_file_permissions option for filesystem attachments -* Improvement: Add Attachment#as_json -* Improvement: Evaluate lambdas for fog_file properties -* Improvement: Extract geometry parsing into factories -* Improvement: Fixed various typos -* Improvement: Refactored some tests -* Improvement: Reuse S3 connections - -New In 3.3.1: - -* Bug Fix: Moved Filesystem's copy_to_local_file to the right place. - -3.3.0: - -* Improvement: Upgrade cocaine to 0.4 - -3.2.0: - -* Bug Fix: Use the new correct Amazon S3 encryption header. -* Bug Fix: The rake task respects the updated_at column. -* Bug Fix: Strip newline from content type. -* Feature: Fog file visibility can be specified per style. -* Feature: Automatically rotate images. -* Feature: Reduce class-oriented programming of the attachment definitions. - -3.1.4: - -* Bug Fix: Allow user to be able to set path without `:style` attribute and not raising an error. - This is a regression introduced in 3.1.3, and that feature will be postponed to another minor - release instead. -* Feature: Allow for URI Adapter as an optional paperclip io adapter. - -3.1.3: - -* Bug Fix: Copy empty attachment between instances is now working. -* Bug Fix: Correctly rescue Fog error. -* Bug Fix: Using default path and url options in Fog storage now work as expected. -* Bug Fix: `Attachment#s3_protocol` now returns a protocol without colon suffix. -* Feature: Paperclip will now raise an error if multiple styles are defined but no `:style` - interpolation exists in `:path`. -* Feature: Add support for `#{attachment}_created_at` field -* Bug Fix: Paperclip now gracefully handles msising file command. -* Bug Fix: `StringIOAdapter` now accepts content type. - -3.1.2: - -* Bug Fix: #remove_attachment on 3.1.0 and 3.1.1 mistakenly trying to remove the column that has - the same name as data type (such as :string, :datetime, :interger.) You're advised to update to - Paperclip 3.1.2 as soon as possible. - -3.1.1: - -* Bug Fix: Paperclip will only load Paperclip::Schema only when Active Record is available. - -3.1.0: - -* Feature: Paperclip now support new migration syntax (sexy migration) that reads better: - - class AddAttachmentToUsers < ActiveRecord::Migration - def self.up - create_table :users do |t| - t.attachment :avatar - end - end - end - - Also, schema-definition level syntax has been added: - - add_attachment :users, :avatar - remove_attachment :users, :avatar - -* Feature: Migration now support Rails 3.2+ `change` method. -* API CHANGE: Old `t.has_attached_file` and `drop_attached_file` are now deprecated. You're advised - to update your migration file before the next MAJOR version. -* Bug Fix: Tempfile now rewinded before generating fingerprint -* API CHANGE: Tempfiles are now unlinked after `after_flush_writes` - - If you need to interact with the generated tempfiles, please define an `after_flush_writes` method - in your model. You'll be able to access files via `@queue_for_write` instance variable. - -* Bug Fix: `:s3_protocol` can now be defined as either String or Symbol -* Bug Fix: Tempfiles are now rewinded before get passed into `after_flush_writes` -* Feature: Added expiring_url method to Fog Storage -* API CHANGE: Paperclip now tested against AWS::SDK 1.5.2 onward -* Bug Fix: Improved the output of the content_type validator so the actual failure is displayed -* Feature: Animated formats now identified using ImageMagick. -* Feature: AttachmentAdapter now support fetching attachment with specific style. -* Feature: Paperclip default options can now be configured in Rails.configuration. -* Feature: add Geometry#resize_to to calculate dimensions of new source. -* Bug Fix: Fixed a bug whereby a file type with multiple mime types but no official type would cause - the best_content_type to throw an error on trying nil.content_type. -* Bug Fix: Fix problem when the gem cannot be installed on the system that has Asepsis installed. - -3.0.4: - -* Feature: Adds support for S3 scheme-less URL generation. - -3.0.3: - -* Bug Fix: ThumbnailProcessor now correctly detects and preserve animated GIF. -* Bug Fix: File extension is now preserved in generated Tempfile from adapter. -* Bug Fix: Uploading file with unicode file name now won't raise an error when - logging in the AWS is turned on. -* Bug Fix: Task "paperclip:refresh:missing_styles" now work correctly. -* Bug Fix: Handle the case when :restricted_characters is nil. -* Bug Fix: Don't delete all the existing styles if we reprocess. -* Bug Fix: Content type is now ensured to not having a new line character. -* API CHANGE: Non-Rails usage should include Paperclip::Glue directly. - - `Paperclip::Railtie` was intended to be used with Ruby on Rails only. If you're - using Paperclip without Rails, you should include `Paperclip::Glue` into - `ActiveRecord::Base` instead of requiring `paperclip/railtie`: - - ActiveRecord::Base.send :include, Paperclip::Glue - -* Bug Fix: AttachmentContentTypeValidator now allow you to specify :allow_blank/:allow_nil -* Bug Fix: Make sure content type always a String. -* Bug Fix: Fix attachment.reprocess! when using storage providers fog and s3. -* Bug Fix: Fix a problem with incorrect content_type detected with 'file' command for an empty file on Mac. - -3.0.2: - -* API CHANGE: Generated migration class name is now plural (AddAttachmentToUsers instead of AddAttachmentToUser) -* API CHANGE: Remove Rails plugin initialization code. -* API CHANGE: Explicitly require Ruby 1.9.2 in the Gemfile. -* Bug Fix: Fixes AWS::S3::Errors::RequestTimeout on Model#save. -* Bug Fix: Fix a problem when there's no logger specified. -* Bug Fix: Fix a problem when attaching Rack::Test::UploadedFile instance. - -3.0.1: - -* Feature: Introduce Paperlip IO adapter. -* Bug Fix: Regression in AttachmentContentTypeValidator has been fixed. -* API CHANGE: #to_file has been removed. Use the #copy_to_local_file method instead. - -3.0.0: - -* API CHANGE: Paperclip now requires at least Ruby on Rails version 3.0.0 -* API CHANGE: The default :url and :path have changed. The new scheme avoids - filesystem conflicts and scales to handle larger numbers of uploads. - - The easiest way to upgrade is to add an explicit :url and :path to your - has_attached_file calls: - - has_attached_file :avatar, - :path => ":rails_root/public/system/:attachment/:id/:style/:filename", - :url => "/system/:attachment/:id/:style/:filename" - -* Feature: Adding Rails 3 style validators, and adding `validates_attachment` method as a shorthand. -* Bug Fix: Paperclip's rake tasks now loading records in batch. -* Bug Fix: Attachment style name with leading number now not raising an error. -* Bug Fix: File given to S3 and Fog storage will now be rewinded after flush_write. -* Feature: You can now pass addional parameter to S3 expiring URL, such as :content_type. - -2.7.0: - -* Bug Fix: Checking the existence of a file on S3 handles all AWS errors. -* Bug Fix: Clear the fingerprint when removing an attachment. -* Bug Fix: Attachment size validation message reads more nicely now. -* Feature: Style names can be either symbols or strings. -* Compatibility: Support for ActiveSupport < 2.3.12. -* Compatibility: Support for Rails 3.2. - -2.6.0: - -* Bug Fix: Files are re-wound after reading. -* Feature: Remove Rails dependency from specs that need Paperclip. -* Feature: Validation matchers support conditionals. - -2.5.2: - -* Bug Fix: Can be installed on Windows. -* Feature: The Fog bucket name, authentication, and host can be determined at runtime via Proc. -* Feature: Special characters are replaced with underscores in #url and #path. - -2.5.1: - -* Feature: After we've computed the content type, pass it to Fog. -* Feature: S3 encryption with the new :s3_server_side_encryption option. -* Feature: Works without ActiveRecord, allowing for e.g. mongo backends. - -2.5.0: - -* Performance: Only connect to S3 when absolutely needed. -* Bug Fix: STI with cached classes respect new options. -* Bug Fix: conditional validations broke, and now work again. -* Feature: URL generation is now parameterized and can be changed with plugins or custom code. -* Feature: :convert_options and :source_file_options to control the ImageMagick processing. -* Performance: String geometry specifications now parse more quickly. -* Bug Fix: Handle files with question marks in the filename. -* Bug Fix: Don't raise an error when generating an expiring URL on an unassigned attachment. -* Bug Fix: The rake task runs over all instances of an ActiveRecord model, ignoring default scopes. -* Feature: DB migration has_attached_file and drop_attached_file methods. -* Bug Fix: Switch from AWS::S3 to AWS::SDK for the S3 backend. -* Bug Fix: URL generator uses '?' in the URL unless it already appears and there is no prior '='. -* Bug Fix: Always convert the content type to a string before stripping blanks. -* Feature: The :keep_old_files option preserves the files in storage even when the attachment is cleared or changed. -* Performance: Optimize Fog's public_url access by avoiding it when possible. -* Bug Fix: Avoid a runtime error when generating the ID partition for an unsaved attachment. -* Performance: Do not calculate the fingerprint if it is never persisted. -* Bug Fix: Process the :original style before all others, in case of a dependency. -* Feature: S3 headers can be set at runtime by passing a proc object as the value. -* Bug Fix: Generating missing attachment styles for a model which has had its attachment changed should not raise. -* Bug Fix: Do not collide with the built-in Ruby hashing method. diff --git a/README.md b/README.md deleted file mode 100644 index 697181d0b..000000000 --- a/README.md +++ /dev/null @@ -1,1094 +0,0 @@ -Paperclip -========= - -# Deprecated - -**[Paperclip is deprecated]**. - -For new projects, we recommend Rails' own [ActiveStorage]. - -For existing projects, please consult and contribute to the migration guide, -available [in English], [en español], and as [a video] recorded at RailsConf -2019. - -Alternatively, for existing projects, [Kreeti] is maintaining [kt-paperclip], -an ongoing [fork of Paperclip]. - -We will leave the Issues open as a discussion forum _only_. We do _not_ -guarantee a response from us in the Issues. All bug reports should go to -kt-paperclip. - -We are no longer accepting pull requests _except_ pull requests against the -migration guide. All other pull requests will be closed without merging. - -[Paperclip is deprecated]: https://robots.thoughtbot.com/closing-the-trombone -[ActiveStorage]: http://guides.rubyonrails.org/active_storage_overview.html -[in English]: https://github.com/thoughtbot/paperclip/blob/master/MIGRATING.md -[en español]: https://github.com/thoughtbot/paperclip/blob/master/MIGRATING-ES.md -[a video]: https://www.youtube.com/watch?v=tZ_WNUytO9o -[Kreeti]: https://www.kreeti.com/ -[kt-paperclip]: https://rubygems.org/gems/kt-paperclip -[fork of Paperclip]: https://github.com/kreeti/kt-paperclip - -# Existing documentation - -## Documentation valid for `master` branch - -Please check the documentation for the paperclip version you are using: -https://github.com/thoughtbot/paperclip/releases - ---- - -[![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) - - - - -- [Requirements](#requirements) - - [Ruby and Rails](#ruby-and-rails) - - [Image Processor](#image-processor) - - [`file`](#file) -- [Installation](#installation) -- [Quick Start](#quick-start) - - [Models](#models) - - [Migrations](#migrations) - - [Edit and New Views](#edit-and-new-views) - - [Edit and New Views with Simple Form](#edit-and-new-views-with-simple-form) - - [Controller](#controller) - - [View Helpers](#view-helpers) - - [Checking a File Exists](#checking-a-file-exists) - - [Deleting an Attachment](#deleting-an-attachment) -- [Usage](#usage) -- [Validations](#validations) -- [Internationalization (I18n)](#internationalization-i18n) -- [Security Validations](#security-validations) -- [Defaults](#defaults) -- [Migrations](#migrations-1) - - [Add Attachment Column To A Table](#add-attachment-column-to-a-table) - - [Schema Definition](#schema-definition) - - [Vintage Syntax](#vintage-syntax) -- [Storage](#storage) - - [Understanding Storage](#understanding-storage) -- [IO Adapters](#io-adapters) -- [Post Processing](#post-processing) -- [Custom Attachment Processors](#custom-attachment-processors) -- [Events](#events) -- [URI Obfuscation](#uri-obfuscation) -- [Checksum / Fingerprint](#checksum--fingerprint) -- [File Preservation for Soft-Delete](#file-preservation-for-soft-delete) -- [Dynamic Configuration](#dynamic-configuration) - - [Dynamic Styles:](#dynamic-styles) - - [Dynamic Processors:](#dynamic-processors) -- [Logging](#logging) -- [Deployment](#deployment) - - [Attachment Styles](#attachment-styles) -- [Testing](#testing) -- [Contributing](#contributing) -- [License](#license) -- [About thoughtbot](#about-thoughtbot) - - - -Paperclip is intended as an easy file attachment library for ActiveRecord. The -intent behind it was to keep setup as easy as possible and to treat files as -much like other attributes as possible. This means they aren't saved to their -final locations on disk, nor are they deleted if set to nil, until -ActiveRecord::Base#save is called. It manages validations based on size and -presence, if required. It can transform its assigned image into thumbnails if -needed, and the prerequisites are as simple as installing ImageMagick (which, -for most modern Unix-based systems, is as easy as installing the right -packages). Attached files are saved to the filesystem and referenced in the -browser by an easily understandable specification, which has sensible and -useful defaults. - -See the documentation for `has_attached_file` in [`Paperclip::ClassMethods`](http://www.rubydoc.info/gems/paperclip/Paperclip/ClassMethods) for -more detailed options. - -The complete [RDoc](http://www.rubydoc.info/gems/paperclip) is online. - ---- - -Requirements ------------- - -### Ruby and Rails - -Paperclip now requires Ruby version **>= 2.1** and Rails version **>= 4.2** -(only if you're going to use Paperclip with Ruby on Rails). - -### Image Processor - -[ImageMagick](http://www.imagemagick.org) must be installed and Paperclip must have access to it. To ensure -that it does, on your command line, run `which convert` (one of the ImageMagick -utilities). This will give you the path where that utility is installed. For -example, it might return `/usr/local/bin/convert`. - -Then, in your environment config file, let Paperclip know to look there by adding that -directory to its path. - -In development mode, you might add this line to `config/environments/development.rb)`: - -```ruby -Paperclip.options[:command_path] = "/usr/local/bin/" -``` - -If you're on Mac OS X, you'll want to run the following with [Homebrew](http://www.brew.sh): - - brew install imagemagick - -If you are dealing with pdf uploads or running the test suite, you'll also need -to install GhostScript. On Mac OS X, you can also install that using Homebrew: - - brew install gs - -If you are on Ubuntu (or any Debian base Linux distribution), you'll want to run -the following with apt-get: - - sudo apt-get install imagemagick -y - -### `file` - -The Unix [`file` command](https://en.wikipedia.org/wiki/File_(command)) is required for content-type checking. -This utility isn't available in Windows, but comes bundled with Ruby [Devkit](https://github.com/oneclick/rubyinstaller/wiki/Development-Kit), -so Windows users must make sure that the devkit is installed and added to the system `PATH`. - -**Manual Installation** - -If 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. - -To manually install, you should perform the following: - -> **Download & install `file` from [this URL](http://gnuwin32.sourceforge.net/packages/file.htm)** - -To test, you can use the image below: -![untitled](https://cloud.githubusercontent.com/assets/1104431/4524452/a1f8cce4-4d44-11e4-872e-17adb96f79c9.png) - -Next, you need to integrate with your environment - preferably through the `PATH` variable, or by changing your `config/environments/development.rb` file - -**PATH** - - 1. Click "Start" - 2. On "Computer", right-click and select "Properties" - 3. In Properties, select "Advanced System Settings" - 4. Click the "Environment Variables" button - 5. Locate the "PATH" var - at the end, add the path to your newly installed `file.exe` (typically `C:\Program Files (x86)\GnuWin32\bin`) - 6. Restart any CMD shells you have open & see if it works - -OR - -**Environment** - - 1. Open `config/environments/development.rb` - 2. Add the following line: `Paperclip.options[:command_path] = 'C:\Program Files (x86)\GnuWin32\bin'` - 3. Restart your Rails server - -Either 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) - ---- - -Installation ------------- - -Paperclip is distributed as a gem, which is how it should be used in your app. - -Include the gem in your Gemfile: - -```ruby -gem "paperclip", "~> 6.0.0" -``` - -Or, if you want to get the latest, you can get master from the main paperclip repository: - -```ruby -gem "paperclip", git: "git://github.com/thoughtbot/paperclip.git" -``` - -If you're trying to use features that don't seem to be in the latest released gem, but are -mentioned in this README, then you probably need to specify the master branch if you want to -use them. This README is probably ahead of the latest released version if you're reading it -on GitHub. - -For Non-Rails usage: - -```ruby -class ModuleName < ActiveRecord::Base - include Paperclip::Glue - ... -end -``` - ---- - -Quick Start ------------ - -### Models - -```ruby -class User < ActiveRecord::Base - has_attached_file :avatar, styles: { medium: "300x300>", thumb: "100x100>" }, default_url: "/images/:style/missing.png" - validates_attachment_content_type :avatar, content_type: /\Aimage\/.*\z/ -end -``` - -### Migrations - - -Assuming you have a `users` table, add an `avatar` column to the `users` table: -```ruby -class AddAvatarColumnsToUsers < ActiveRecord::Migration - def up - add_attachment :users, :avatar - end - - def down - remove_attachment :users, :avatar - end -end -``` - -(Or you can use the Rails migration generator: `rails generate paperclip user avatar`) - -### Edit and New Views -Make sure you have corresponding methods in your controller: -```erb -<%= form_for @user, url: users_path, html: { multipart: true } do |form| %> - <%= form.file_field :avatar %> - <%= form.submit %> -<% end %> -``` - -### Edit and New Views with [Simple Form](https://github.com/plataformatec/simple_form) - -```erb -<%= simple_form_for @user, url: users_path do |form| %> - <%= form.input :avatar, as: :file %> - <%= form.submit %> -<% end %> -``` - -### Controller - -```ruby -def create - @user = User.create(user_params) -end - -private - -# Use strong_parameters for attribute whitelisting -# Be sure to update your create() and update() controller methods. - -def user_params - params.require(:user).permit(:avatar) -end -``` - -### View Helpers -Add these to the view where you want your images displayed: -```erb -<%= image_tag @user.avatar.url %> -<%= image_tag @user.avatar.url(:medium) %> -<%= image_tag @user.avatar.url(:thumb) %> -``` - -### Checking a File Exists - -There are two methods for checking if a file exists: - -- `file?` and `present?` checks if the `_file_name` field is populated -- `exists?` checks if the file exists (will perform a TCP connection if stored in the cloud) - -Keep this in mind if you are checking if files are present in a loop. The first -version is significantly more performant, but has different semantics. - -### Deleting an Attachment - -Set the attribute to `nil` and save. - -```ruby -@user.avatar = nil -@user.save -``` ---- - -Usage ------ - -The basics of Paperclip are quite simple: Declare that your model has an -attachment with the `has_attached_file` method, and give it a name. - -Paperclip will wrap up to four attributes (all prefixed with that attachment's name, -so you can have multiple attachments per model if you wish) and give them a -friendly front end. These attributes are: - -* `_file_name` -* `_file_size` -* `_content_type` -* `_updated_at` - -By default, only `_file_name` is required for Paperclip to operate. -You'll need to add `_content_type` in case you want to use content type -validation. - -More information about the options passed to `has_attached_file` is available in the -documentation of [`Paperclip::ClassMethods`](http://www.rubydoc.info/gems/paperclip/Paperclip/ClassMethods). - -Validations ------------ - -For validations, Paperclip introduces several validators to validate your attachment: - -* `AttachmentContentTypeValidator` -* `AttachmentPresenceValidator` -* `AttachmentSizeValidator` - -Example Usage: - -```ruby -validates :avatar, attachment_presence: true -validates_with AttachmentPresenceValidator, attributes: :avatar -validates_with AttachmentSizeValidator, attributes: :avatar, less_than: 1.megabytes - -``` - -Validators can also be defined using the old helper style: - -* `validates_attachment_presence` -* `validates_attachment_content_type` -* `validates_attachment_size` - -Example Usage: - -```ruby -validates_attachment_presence :avatar -``` - -Lastly, you can also define multiple validations on a single attachment using `validates_attachment`: - -```ruby -validates_attachment :avatar, presence: true, - content_type: "image/jpeg", - size: { in: 0..10.kilobytes } -``` - -_NOTE: Post-processing will not even **start** if the attachment is not valid -according to the validations. Your callbacks and processors will **only** be -called with valid attachments._ - -```ruby -class Message < ActiveRecord::Base - has_attached_file :asset, styles: { thumb: "100x100#" } - - before_post_process :skip_for_audio - - def skip_for_audio - ! %w(audio/ogg application/ogg).include?(asset_content_type) - end -end -``` - -If you have other validations that depend on assignment order, the recommended -course of action is to prevent the assignment of the attachment until -afterwards, then assign manually: - -```ruby -class Book < ActiveRecord::Base - has_attached_file :document, styles: { thumbnail: "60x60#" } - validates_attachment :document, content_type: "application/pdf" - validates_something_else # Other validations that conflict with Paperclip's -end - -class BooksController < ApplicationController - def create - @book = Book.new(book_params) - @book.document = params[:book][:document] - @book.save - respond_with @book - end - - private - - def book_params - params.require(:book).permit(:title, :author) - end -end -``` - -**A note on content_type validations and security** - -You should ensure that you validate files to be only those MIME types you -explicitly want to support. If you don't, you could be open to -XSS attacks -if a user uploads a file with a malicious HTML payload. - -If you're only interested in images, restrict your allowed content_types to -image-y ones: - -```ruby -validates_attachment :avatar, - content_type: ["image/jpeg", "image/gif", "image/png"] -``` - -`Paperclip::ContentTypeDetector` will attempt to match a file's extension to an -inferred content_type, regardless of the actual contents of the file. - ---- - -Internationalization (I18n) ---------------------------- - -For using or adding locale files in different languages, check the project -https://github.com/thoughtbot/paperclip-i18n. - -Security Validations -==================== - -Thanks to a report from [Egor Homakov](http://homakov.blogspot.com/) we have -taken steps to prevent people from spoofing Content-Types and getting data -you weren't expecting onto your server. - -NOTE: Starting at version 4.0.0, all attachments are *required* to include a -content_type validation, a file_name validation, or to explicitly state that -they're not going to have either. *Paperclip will raise an error* if you do not -do this. - -```ruby -class ActiveRecord::Base - has_attached_file :avatar - # Validate content type - validates_attachment_content_type :avatar, content_type: /\Aimage/ - # Validate filename - validates_attachment_file_name :avatar, matches: [/png\z/, /jpe?g\z/] - # Explicitly do not validate - do_not_validate_attachment_file_type :avatar -end -``` - -This keeps Paperclip secure-by-default, and will prevent people trying to mess -with your filesystem. - -NOTE: Also starting at version 4.0.0, Paperclip has another validation that -cannot be turned off. This validation will prevent content type spoofing. That -is, uploading a PHP document (for example) as part of the EXIF tags of a -well-formed JPEG. This check is limited to the media type (the first part of the -MIME type, so, 'text' in `text/plain`). This will prevent HTML documents from -being uploaded as JPEGs, but will not prevent GIFs from being uploaded with a -`.jpg` extension. This validation will only add validation errors to the form. It -will not cause errors to be raised. - -This can sometimes cause false validation errors in applications that use custom -file extensions. In these cases you may wish to add your custom extension to the -list of content type mappings by creating `config/initializers/paperclip.rb`: - -```ruby -# Allow ".foo" as an extension for files with the MIME type "text/plain". -Paperclip.options[:content_type_mappings] = { - foo: %w(text/plain) -} -``` - ---- - -Defaults --------- -Global 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. - -If 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: - -```ruby -module YourApp - class Application < Rails::Application - # Other code... - - config.paperclip_defaults = { storage: :fog, fog_credentials: { provider: "Local", local_root: "#{Rails.root}/public"}, fog_directory: "", fog_host: "localhost"} - end -end -``` - -Another 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. - -An example Rails initializer would look something like this: - -```ruby -Paperclip::Attachment.default_options[:storage] = :fog -Paperclip::Attachment.default_options[:fog_credentials] = { provider: "Local", local_root: "#{Rails.root}/public"} -Paperclip::Attachment.default_options[:fog_directory] = "" -Paperclip::Attachment.default_options[:fog_host] = "http://localhost:3000" -``` ---- - -Migrations ----------- - -Paperclip defines several migration methods which can be used to create the necessary columns in your -model. There are two types of helper methods to aid in this, as follows: - -### Add Attachment Column To A Table - -The `attachment` helper can be used when creating a table: - -```ruby -class CreateUsersWithAttachments < ActiveRecord::Migration - def up - create_table :users do |t| - t.attachment :avatar - end - end - - # This is assuming you are only using the users table for Paperclip attachment. Drop with care! - def down - drop_table :users - end -end -``` - -You can also use the `change` method, instead of the `up`/`down` combination above, as shown below: - -```ruby -class CreateUsersWithAttachments < ActiveRecord::Migration - def change - create_table :users do |t| - t.attachment :avatar - end - end -end -``` - -### Schema Definition - -Alternatively, the `add_attachment` and `remove_attachment` methods can be used to add new Paperclip columns to an existing table: - -```ruby -class AddAttachmentColumnsToUsers < ActiveRecord::Migration - def up - add_attachment :users, :avatar - end - - def down - remove_attachment :users, :avatar - end -end -``` - -Or you can do this with the `change` method: - -```ruby -class AddAttachmentColumnsToUsers < ActiveRecord::Migration - def change - add_attachment :users, :avatar - end -end -``` - -### Vintage Syntax - -Vintage syntax (such as `t.has_attached_file` and `drop_attached_file`) is still supported in -Paperclip 3.x, but you're advised to update those migration files to use this new syntax. - ---- - -Storage -------- - -Paperclip ships with 3 storage adapters: - -* File Storage -* S3 Storage (via `aws-sdk-s3`) -* Fog Storage - -If you would like to use Paperclip with another storage, you can install these -gems along side with Paperclip: - -* [paperclip-azure](https://github.com/supportify/paperclip-azure) -* [paperclip-azure-storage](https://github.com/gmontard/paperclip-azure-storage) -* [paperclip-dropbox](https://github.com/janko-m/paperclip-dropbox) - -### Understanding Storage - -The files that are assigned as attachments are, by default, placed in the -directory specified by the `:path` option to `has_attached_file`. By default, this -location is `:rails_root/public/system/:class/:attachment/:id_partition/:style/:filename`. -This location was chosen because, on standard Capistrano deployments, the -`public/system` directory can be symlinked to the app's shared directory, meaning it -survives between deployments. For example, using that `:path`, you may have a -file at - - /data/myapp/releases/20081229172410/public/system/users/avatar/000/000/013/small/my_pic.png - -_**NOTE**: This is a change from previous versions of Paperclip, but is overall a -safer choice for the default file store._ - -You may also choose to store your files using Amazon's S3 service. To do so, include -the `aws-sdk-s3` gem in your Gemfile: - -```ruby -gem 'aws-sdk-s3' -``` - -And then you can specify using S3 from `has_attached_file`. -You can find more information about configuring and using S3 storage in -[the `Paperclip::Storage::S3` documentation](http://www.rubydoc.info/gems/paperclip/Paperclip/Storage/S3). - -Files on the local filesystem (and in the Rails app's public directory) will be -available to the internet at large. If you require access control, it's -possible to place your files in a different location. You will need to change -both the `:path` and `:url` options in order to make sure the files are unavailable -to the public. Both `:path` and `:url` allow the same set of interpolated -variables. - ---- - -IO Adapters ------------ - -When a file is uploaded or attached, it can be in one of a few different input -forms, from Rails' UploadedFile object to a StringIO to a Tempfile or even a -simple String that is a URL that points to an image. - -Paperclip will accept, by default, many of these sources. It also is capable of -handling even more with a little configuration. The IO Adapters that handle -images from non-local sources are not enabled by default. They can be enabled by -adding a line similar to the following into `config/initializers/paperclip.rb`: - -```ruby -Paperclip::DataUriAdapter.register -``` - -It's best to only enable a remote-loading adapter if you need it. Otherwise -there's a chance that someone can gain insight into your internal network -structure using it as a vector. - -The following adapters are *not* loaded by default: - -* `Paperclip::UriAdapter` - which accepts a `URI` instance. -* `Paperclip::HttpUrlProxyAdapter` - which accepts a `http` string. -* `Paperclip::DataUriAdapter` - which accepts a Base64-encoded `data:` string. - ---- - -Post Processing ---------------- - -Paperclip supports an extensible selection of post-processors. When you define -a set of styles for an attachment, by default it is expected that those -"styles" are actually "thumbnails." These are processed by -`Paperclip::Thumbnail`. For backward compatibility reasons you can pass either -a single geometry string, or an array containing a geometry and a format that -the file will be converted to, like so: - -```ruby -has_attached_file :avatar, styles: { thumb: ["32x32#", :png] } -``` - -This will convert the "thumb" style to a 32x32 square in PNG format, regardless -of what was uploaded. If the format is not specified, it is kept the same (e.g. -JPGs will remain JPGs). `Paperclip::Thumbnail` uses ImageMagick to process -images; [ImageMagick's geometry documentation](http://www.imagemagick.org/script/command-line-processing.php#geometry) -has more information on the accepted style formats. - -For 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: - -```ruby -has_attached_file :image, styles: { regular: ['800x800>', :png]}, - source_file_options: { regular: "-density 96 -depth 8 -quality 85" }, - convert_options: { regular: "-posterize 3"} -``` - -ImageMagick 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: - -* `MAGICK_MEMORY_LIMIT=128MiB` -* `MAGICK_MAP_LIMIT=64MiB` -* `MAGICK_TIME_LIMIT=30` - -For a full list of variables and description, see [ImageMagick's resources documentation](http://www.imagemagick.org/script/resources.php). - ---- - -Custom Attachment Processors -------- - -You can write your own custom attachment processors to carry out tasks like -adding watermarks, compressing images, or encrypting files. Custom processors -must be defined within the `Paperclip` module, inherit from -`Paperclip::Processor` (see [`lib/paperclip/processor.rb`](https://github.com/thoughtbot/paperclip/blob/master/lib/paperclip/processor.rb)), -and implement a `make` method that returns a `File`. All files in your Rails -app's `lib/paperclip` and `lib/paperclip_processors` directories will be -automatically loaded by Paperclip. Processors are specified using the -`:processors` option to `has_attached_file`: - -```ruby -has_attached_file :scan, styles: { text: { quality: :better } }, - processors: [:ocr] -``` - -This would load the hypothetical class `Paperclip::Ocr`, and pass it the -options hash `{ quality: :better }`, along with the uploaded file. - -Multiple processors can be specified, and they will be invoked in the order -they are defined in the `:processors` array. Each successive processor is given -the result from the previous processor. All processors receive the same -parameters, which are defined in the `:styles` hash. For example, assuming we -had this definition: - -```ruby -has_attached_file :scan, styles: { text: { quality: :better } }, - processors: [:rotator, :ocr] -``` - -Both the `:rotator` processor and the `:ocr` processor would receive the -options `{ quality: :better }`. If a processor receives an option it doesn't -recognise, it's expected to ignore it. - -_NOTE: Because processors operate by turning the original attachment into the -styles, no processors will be run if there are no styles defined._ - -If you're interested in caching your thumbnail's width, height and size in the -database, take a look at the [paperclip-meta](https://github.com/teeparham/paperclip-meta) -gem. - -Also, if you're interested in generating the thumbnail on-the-fly, you might want -to look into the [attachment_on_the_fly](https://github.com/drpentode/Attachment-on-the-Fly) -gem. - -Paperclip's thumbnail generator (see [`lib/paperclip/thumbnail.rb`](lib/paperclip/thumbnail.rb)) -is implemented as a processor, and may be a good reference for writing your own -processors. - ---- - -Events ------- - -Before and after the Post Processing step, Paperclip calls back to the model -with a few callbacks, allowing the model to change or cancel the processing -step. The callbacks are `before_post_process` and `after_post_process` (which -are called before and after the processing of each attachment), and the -attachment-specific `before__post_process` and -`after__post_process`. The callbacks are intended to be as close to -normal ActiveRecord callbacks as possible, so if you return false (specifically -\- returning nil is not the same) in a `before_filter`, the post processing step -will halt. Returning false in an `after_filter` will not halt anything, but you -can access the model and the attachment if necessary. - -_NOTE: Post processing will not even **start** if the attachment is not valid -according to the validations. Your callbacks and processors will **only** be -called with valid attachments._ - -```ruby -class Message < ActiveRecord::Base - has_attached_file :asset, styles: { thumb: "100x100#" } - - before_post_process :skip_for_audio - - def skip_for_audio - ! %w(audio/ogg application/ogg).include?(asset_content_type) - end -end -``` - ---- - -URI Obfuscation ---------------- - -Paperclip has an interpolation called `:hash` for obfuscating filenames of -publicly-available files. - -Example Usage: - -```ruby -has_attached_file :avatar, { - url: "/system/:hash.:extension", - hash_secret: "longSecretString" -} -``` - - -The `:hash` interpolation will be replaced with a unique hash made up of whatever -is specified in `:hash_data`. The default value for `:hash_data` is `":class/:attachment/:id/:style/:updated_at"`. - -`:hash_secret` is required - an exception will be raised if `:hash` is used without `:hash_secret` present. - -For more on this feature, read [the author's own explanation](https://github.com/thoughtbot/paperclip/pull/416) - -Checksum / Fingerprint -------- - -A checksum of the original file assigned will be placed in the model if it -has an attribute named fingerprint. Following the user model migration example -above, the migration would look like the following: - -```ruby -class AddAvatarFingerprintColumnToUser < ActiveRecord::Migration - def up - add_column :users, :avatar_fingerprint, :string - end - - def down - remove_column :users, :avatar_fingerprint - end -end -``` - -The algorithm can be specified using a configuration option; it defaults to MD5 -for backwards compatibility with Paperclip 5 and earlier. - -```ruby -has_attached_file :some_attachment, adapter_options: { hash_digest: Digest::SHA256 } -``` - -Run `CLASS=User ATTACHMENT=avatar rake paperclip:refresh:fingerprints` after -changing the digest on existing attachments to update the fingerprints in the -database. - -File Preservation for Soft-Delete -------- - -An option is available to preserve attachments in order to play nicely with soft-deleted models. (acts_as_paranoid, paranoia, etc.) - -```ruby -has_attached_file :some_attachment, { - preserve_files: true, -} -``` - -This will prevent ```some_attachment``` from being wiped out when the model gets destroyed, so it will still exist when the object is restored later. - ---- - -Dynamic Configuration ---------------------- - -Callable objects (lambdas, Procs) can be used in a number of places for dynamic -configuration throughout Paperclip. This strategy exists in a number of -components of the library but is most significant in the possibilities for -allowing custom styles and processors to be applied for specific model -instances, rather than applying defined styles and processors across all -instances. - -### Dynamic Styles: - -Imagine a user model that had different styles based on the role of the user. -Perhaps some users are bosses (e.g. a User model instance responds to `#boss?`) -and merit a bigger avatar thumbnail than regular users. The configuration to -determine what style parameters are to be used based on the user role might -look as follows where a boss will receive a `300x300` thumbnail otherwise a -`100x100` thumbnail will be created. - -```ruby -class User < ActiveRecord::Base - has_attached_file :avatar, styles: lambda { |attachment| { thumb: (attachment.instance.boss? ? "300x300>" : "100x100>") } } -end -``` - -### Dynamic Processors: - -Another contrived example is a user model that is aware of which file processors -should be applied to it (beyond the implied `thumbnail` processor invoked when -`:styles` are defined). Perhaps we have a watermark processor available and it is -only used on the avatars of certain models. The configuration for this might be -where the instance is queried for which processors should be applied to it. -Presumably some users might return `[:thumbnail, :watermark]` for its -processors, where a defined `watermark` processor is invoked after the -`thumbnail` processor already defined by Paperclip. - -```ruby -class User < ActiveRecord::Base - has_attached_file :avatar, processors: lambda { |instance| instance.processors } - attr_accessor :processors -end -``` - ---- - -Logging ----------- - -By 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: -```ruby -Your::Application.configure do -... - Paperclip.options[:log] = false -... -end -``` - -More information in the [rdocs](http://www.rubydoc.info/github/thoughtbot/paperclip/Paperclip.options) - ---- - -Deployment ----------- - -To make Capistrano symlink the `public/system` directory so that attachments -survive new deployments, set the `linked_dirs` option in your `config/deploy.rb` -file: - -```ruby -set :linked_dirs, fetch(:linked_dirs, []).push('public/system') -``` - -### Attachment Styles - -Paperclip is aware of new attachment styles you have added in previous deploys. The only thing you should do after each deployment is to call -`rake paperclip:refresh:missing_styles`. It will store current attachment styles in `RAILS_ROOT/public/system/paperclip_attachments.yml` -by default. You can change it by: - -```ruby -Paperclip.registered_attachments_styles_path = '/tmp/config/paperclip_attachments.yml' -``` - -Here is an example for Capistrano: - -```ruby -namespace :paperclip do - desc "build missing paperclip styles" - task :build_missing_styles do - on roles(:app) do - within release_path do - with rails_env: fetch(:rails_env) do - execute :rake, "paperclip:refresh:missing_styles" - end - end - end - end -end - -after("deploy:compile_assets", "paperclip:build_missing_styles") -``` - -Now you don't have to remember to refresh thumbnails in production every time you add a new style. -Unfortunately, it does not work with dynamic styles - it just ignores them. - -If you already have a working app and don't want `rake paperclip:refresh:missing_styles` to refresh old pictures, you need to tell -Paperclip about existing styles. Simply create a `paperclip_attachments.yml` file by hand. For example: - -```ruby -class User < ActiveRecord::Base - has_attached_file :avatar, styles: { thumb: 'x100', croppable: '600x600>', big: '1000x1000>' } -end - -class Book < ActiveRecord::Base - has_attached_file :cover, styles: { small: 'x100', large: '1000x1000>' } - has_attached_file :sample, styles: { thumb: 'x100' } -end -``` - -Then in `RAILS_ROOT/public/system/paperclip_attachments.yml`: - -```yml ---- -:User: - :avatar: - - :thumb - - :croppable - - :big -:Book: - :cover: - - :small - - :large - :sample: - - :thumb -``` - ---- - -Testing -------- - -Paperclip provides rspec-compatible matchers for testing attachments. See the -documentation on [Paperclip::Shoulda::Matchers](http://www.rubydoc.info/gems/paperclip/Paperclip/Shoulda/Matchers) -for more information. - -**Parallel Tests** - -Because of the default `path` for Paperclip storage, if you try to run tests in -parallel, you may find that files get overwritten because the same path is being -calculated for them in each test process. While this fix works for -parallel_tests, a similar concept should be used for any other mechanism for -running tests concurrently. - -```ruby -if ENV['PARALLEL_TEST_GROUPS'] - Paperclip::Attachment.default_options[:path] = ":rails_root/public/system/:rails_env/#{ENV['TEST_ENV_NUMBER'].to_i}/:class/:attachment/:id_partition/:filename" -else - Paperclip::Attachment.default_options[:path] = ":rails_root/public/system/:rails_env/:class/:attachment/:id_partition/:filename" -end -``` - -The important part here being the inclusion of `ENV['TEST_ENV_NUMBER']`, or a -similar mechanism for whichever parallel testing library you use. - -**Integration Tests** - -Using integration tests with FactoryBot may save multiple copies of -your test files within the app. To avoid this, specify a custom path in -the `config/environments/test.rb` like so: - -```ruby -Paperclip::Attachment.default_options[:path] = "#{Rails.root}/spec/test_files/:class/:id_partition/:style.:extension" -``` - -Then, make sure to delete that directory after the test suite runs by adding -this to `spec_helper.rb`. - -```ruby -config.after(:suite) do - FileUtils.rm_rf(Dir["#{Rails.root}/spec/test_files/"]) -end -``` - -**Example of test configuration with Factory Bot** - - -```ruby -FactoryBot.define do - factory :user do - avatar { File.new("#{Rails.root}/spec/support/fixtures/image.jpg") } - end -end -``` ---- - -Contributing ------------- - -If you'd like to contribute a feature or bugfix: Thanks! To make sure your -fix/feature has a high chance of being included, please read the following -guidelines: - -1. Post a [pull request](https://github.com/thoughtbot/paperclip/compare/). -2. Make sure there are tests! We will not accept any patch that is not tested. - It's a rare time when explicit tests aren't needed. If you have questions - about writing tests for paperclip, please open a - [GitHub issue](https://github.com/thoughtbot/paperclip/issues/new). - -Please see [`CONTRIBUTING.md`](./CONTRIBUTING.md) for more details on contributing and running test. - -Thank you to all [the contributors](https://github.com/thoughtbot/paperclip/graphs/contributors)! - -License -------- - -Paperclip is Copyright © 2008-2017 thoughtbot, inc. It is free software, and may be -redistributed under the terms specified in the MIT-LICENSE file. - -About thoughtbot ----------------- - -![thoughtbot](http://presskit.thoughtbot.com/images/thoughtbot-logo-for-readmes.svg) - -Paperclip is maintained and funded by thoughtbot. -The names and logos for thoughtbot are trademarks of thoughtbot, inc. - -We love open source software! -See [our other projects][community] or -[hire us][hire] to design, develop, and grow your product. - -[community]: https://thoughtbot.com/community?utm_source=github -[hire]: https://thoughtbot.com?utm_source=github diff --git a/SECURITY.md b/SECURITY.md new file mode 100644 index 000000000..034e84803 --- /dev/null +++ b/SECURITY.md @@ -0,0 +1,21 @@ +# Security Policy + +## Supported Versions + +Use this section to tell people about which versions of your project are +currently being supported with security updates. + +| Version | Supported | +| ------- | ------------------ | +| 5.1.x | :white_check_mark: | +| 5.0.x | :x: | +| 4.0.x | :white_check_mark: | +| < 4.0 | :x: | + +## Reporting a Vulnerability + +Use this section to tell people how to report a vulnerability. + +Tell them where to go, how often they can expect to get an update on a +reported vulnerability, what to expect if the vulnerability is accepted or +declined, etc. diff --git a/file1 b/file1 new file mode 100644 index 000000000..32e62e2c5 --- /dev/null +++ b/file1 @@ -0,0 +1,47 @@ +require 'rubygems' +require 'rspec' +require 'active_record' +require 'active_record/version' +require 'active_support' +require 'active_support/core_ext' +require 'mocha/api' +require 'bourne' +require 'ostruct' +require 'pathname' +require 'activerecord-import' + +ROOT = Pathname(File.expand_path(File.join(File.dirname(__FILE__), '..'))) + +puts "Testing against version #{ActiveRecord::VERSION::STRING}" + +$LOAD_PATH << File.join(ROOT, 'lib') +$LOAD_PATH << File.join(ROOT, 'lib', 'paperclip') +require File.join(ROOT, 'lib', 'paperclip.rb') + +FIXTURES_DIR = File.join(File.dirname(__FILE__), "fixtures") +config = YAML::load(IO.read(File.dirname(__FILE__) + '/database.yml')) +ActiveRecord::Base.logger = Logger.new(File.dirname(__FILE__) + "/debug.log") +ActiveRecord::Base.establish_connection(config['test']) +if ActiveRecord::VERSION::STRING >= "4.2" && + ActiveRecord::VERSION::STRING < "5.0" + ActiveRecord::Base.raise_in_transactional_callbacks = true +end +Paperclip.options[:logger] = ActiveRecord::Base.logger + +Dir[File.join(ROOT, 'spec', 'support', '**', '*.rb')].each{|f| require f } + +Rails = FakeRails.new('test', Pathname.new(ROOT).join('tmp')) +ActiveSupport::Deprecation.silenced = true + +RSpec.configure do |config| + config.include Assertions + config.include ModelReconstruction + config.include TestData + config.include Reporting + config.extend VersionHelper + config.mock_framework = :mocha + config.before(:all) do + rebuild_model + end +end +© 2021 GitHub, Inc.