Skip to content Skip to sidebar Skip to footer

Ruby Upload File and State at Same Page

Paperclip

Deprecated

Paperclip is deprecated.

For new projects, nosotros recommend Runway' 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. You may besides prefer an alternative migration tutorial used by Doorkeeper.

Alternatively, for existing projects, Kreeti is maintaining kt-paperclip, an ongoing fork of Paperclip.

We will leave the Bug open up every bit a discussion forum only. We do not guarantee a response from us in the Issues. All issues reports should become to kt-paperclip.

We are no longer accepting pull requests except pull requests against the migration guide. All other pull requests will exist closed without merging.

Existing documentation

Documentation valid for master co-operative

Please check the documentation for the paperclip version you are using: https://github.com/thoughtbot/paperclip/releases


Build Status Dependency Status Code Climate Inline docs Security

  • Requirements
    • Ruby and Rails
    • Epitome Processor
    • file
  • Installation
  • Quick Commencement
    • Models
    • Migrations
    • Edit and New Views
    • Edit and New Views with Simple Form
    • Controller
    • View Helpers
    • Checking a File Exists
    • Deleting an Attachment
  • Usage
  • Validations
  • Internationalization (I18n)
  • Security Validations
  • Defaults
  • Migrations
    • Add Attachment Cavalcade To A Table
    • Schema Definition
    • Vintage Syntax
  • Storage
    • Agreement Storage
  • IO Adapters
  • Mail Processing
  • Custom Zipper Processors
  • Events
  • URI Obfuscation
  • Checksum / Fingerprint
  • File Preservation for Soft-Delete
  • Dynamic Configuration
    • Dynamic Styles:
    • Dynamic Processors:
  • Logging
  • Deployment
    • Attachment Styles
  • Testing
  • Contributing
  • License
  • Virtually thoughtbot

Paperclip is intended as an easy file attachment library for ActiveRecord. The intent behind it was to go on setup as like shooting fish in a barrel as possible and to treat files every bit much similar other attributes equally possible. This means they aren't saved to their final locations on disk, nor are they deleted if set to nil, until ActiveRecord::Base#salvage is called. It manages validations based on size and presence, if required. It tin transform its assigned image into thumbnails if needed, and the prerequisites are as simple equally installing ImageMagick (which, for most modern Unix-based systems, is as piece of cake every bit installing the right packages). Attached files are saved to the filesystem and referenced in the browser by an hands understandable specification, which has sensible and useful defaults.

Meet the documentation for has_attached_file in Paperclip::ClassMethods for more than detailed options.

The complete RDoc is online.


Requirements

Crimson and Rails

Paperclip now requires Ruby version >= two.1 and Rails version >= 4.two (only if you're going to use Paperclip with Ruby on Rail).

Epitome Processor

ImageMagick must be installed and Paperclip must accept access to it. To ensure that it does, on your control line, run which catechumen (one of the ImageMagick utilities). This volition give you lot the path where that utility is installed. For instance, it might return /usr/local/bin/catechumen.

Then, in your environment config file, let Paperclip know to look there by adding that directory to its path.

In development mode, you lot might add this line to config/environments/development.rb):

              Paperclip              .              options              [              :command_path              ]              =              "/usr/local/bin/"            

If yous're on Mac OS Ten, yous'll want to run the following with Homebrew:

If you are dealing with pdf uploads or running the test suite, yous'll also need to install GhostScript. On Mac Bone X, you can besides install that using Homebrew:

If you are on Ubuntu (or any Debian base Linux distribution), you'll want to run the following with apt-get:

              sudo apt-go install imagemagick -y                          

file

The Unix file command is required for content-type checking. This utility isn't available in Windows, but comes bundled with Ruby Devkit, then Windows users must make sure that the devkit is installed and added to the system PATH.

Manual Installation

If y'all're using Windows seven+ equally a development surround, yous may demand to install the file.exe application manually. The file spoofing system in Paperclip 4+ relies on this; if you don't take it working, you'll receive Validation failed: Upload file has an extension that does non match its contents. errors.

To manually install, yous should perform the following:

Download & install file from this URL

To test, you lot can employ the image below: untitled

Next, you lot need to integrate with your environment - preferably through the PATH variable, or by changing your config/environments/development.rb file

PATH

              i. Click "First" 2. On "Computer", right-click and select "Properties" 3. In Properties, select "Avant-garde System Settings" 4. Click the "Surround Variables" push button 5. Locate the "PATH" var - at the terminate, add together the path to your newly installed `file.exe` (typically `C:\Program Files (x86)\GnuWin32\bin`) six. Restart whatever CMD shells yous have open & see if information technology works                          

OR

Environment

              1. Open `config/environments/evolution.rb` ii. Add the post-obit line: `Paperclip.options[:command_path] = 'C:\Programme Files (x86)\GnuWin32\bin'` three. 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 information technology should be used in your app.

Include the gem in your Gemfile:

              gem              "paperclip"              ,              "~> 6.0.0"            

Or, if you want to get the latest, you can get chief from the primary paperclip repository:

              gem              "paperclip"              ,              git:              "git://github.com/thoughtbot/paperclip.git"            

If you're trying to apply features that don't seem to be in the latest released gem, just are mentioned in this README, and so you probably need to specify the master branch if yous want to use them. This README is probably ahead of the latest released version if you're reading it on GitHub.

For Non-Runway usage:

              course              ModuleName              <              ActiveRecord::Base of operations              include              Paperclip::Glue              ...              end            

Quick Start

Models

              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 tabular array, add an avatar cavalcade to the users tabular array:

              course              AddAvatarColumnsToUsers              <              ActiveRecord::Migration              def              up              add_attachment              :users              ,              :avatar              stop              def              downwardly              remove_attachment              :users              ,              :avatar              end              stop            

(Or you tin use the Runway migration generator: rails generate paperclip user avatar)

Edit and New Views

Make certain you take respective methods in your controller:

              <%=              form_for @user, url: users_path, html: { multipart: truthful } do |form|              %>                                            <%=              form.file_field :avatar              %>                                            <%=              form.submit              %>                            <%              end              %>                                                                                                                                                                                                                                                                                                                  

Edit and New Views with Simple Form

              <%=              simple_form_for @user, url: users_path practise |form|              %>                                            <%=              grade.input :avatar, every bit: :file              %>                                            <%=              class.submit              %>                            <%              end              %>                                                                                                                                                                                                                                                                        

Controller

              def              create              @user              =              User              .              create              (              user_params              )              terminate              private              # Use strong_parameters for attribute whitelisting              # Be sure to update your create() and update() controller methods.              def              user_params              params              .              crave              (              :user              )              .              permit              (              :avatar              )              end            

View Helpers

Add together these to the view where y'all want your images displayed:

              <%=              image_tag @user.avatar.url              %>                            <%=              image_tag @user.avatar.url(:medium)              %>                            <%=              image_tag @user.avatar.url(:thumb)              %>                                                                                                                                                                                                                                                                                                                                                            

Checking a File Exists

At that place are two methods for checking if a file exists:

  • file? and nowadays? checks if the _file_name field is populated
  • exists? checks if the file exists (will perform a TCP connectedness if stored in the cloud)

Keep this in listen if you are checking if files are present in a loop. The starting time version is significantly more performant, but has different semantics.

Deleting an Attachment

Set the attribute to nil and salvage.

              @user              .              avatar              =              nil              @user              .              relieve            

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 iv attributes (all prefixed with that attachment's name, then y'all can have multiple attachments per model if y'all wish) and requite them a friendly front end finish. These attributes are:

  • <zipper>_file_name
  • <attachment>_file_size
  • <attachment>_content_type
  • <attachment>_updated_at

By default, only <zipper>_file_name is required for Paperclip to operate. You'll demand to add <zipper>_content_type in case you want to apply content type validation.

More information near the options passed to has_attached_file is bachelor in the documentation of Paperclip::ClassMethods.

Validations

For validations, Paperclip introduces several validators to validate your attachment:

  • AttachmentContentTypeValidator
  • AttachmentPresenceValidator
  • AttachmentSizeValidator

Example Usage:

              validates              :avatar              ,              attachment_presence:              true              validates_with              AttachmentPresenceValidator              ,              attributes:              :avatar              validates_with              AttachmentSizeValidator              ,              attributes:              :avatar              ,              less_than:              1              .              megabytes            

Validators can also exist defined using the old helper mode:

  • validates_attachment_presence
  • validates_attachment_content_type
  • validates_attachment_size

Example Usage:

              validates_attachment_presence              :avatar            

Lastly, y'all can besides define multiple validations on a single attachment using validates_attachment:

              validates_attachment              :avatar              ,              presence:              true              ,              content_type:              "image/jpeg"              ,              size:              {              in:              0..10              .              kilobytes              }            

Note: Post-processing volition not even start if the attachment is not valid according to the validations. Your callbacks and processors will only be called with valid attachments.

              class              Message              <              ActiveRecord::Base              has_attached_file              :nugget              ,              styles:              {              pollex:              "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 class of action is to forbid the consignment of the zipper until afterwards, then assign manually:

              class              Book              <              ActiveRecord::Base of operations              has_attached_file              :document              ,              styles:              {              thumbnail:              "60x60#"              }              validates_attachment              :document              ,              content_type:              "application/pdf"              validates_something_else              # Other validations that conflict with Paperclip'due south              end              class              BooksController              <              ApplicationController              def              create              @book              =              Book              .              new              (              book_params              )              @book              .              document              =              params              [              :volume              ]              [              :document              ]              @book              .              save              respond_with              @volume              terminate              private              def              book_params              params              .              require              (              :book              )              .              permit              (              :title              ,              :author              )              end              terminate            

A annotation on content_type validations and security

You should ensure that you validate files to exist only those MIME types you explicitly want to support. If you don't, y'all could exist open to XSS attacks if a user uploads a file with a malicious HTML payload.

If you're but interested in images, restrict your immune content_types to image-y ones:

              validates_attachment              :avatar              ,              content_type:              [              "prototype/jpeg"              ,              "epitome/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 calculation locale files in different languages, bank check the project https://github.com/thoughtbot/paperclip-i18n.

Security Validations

Thanks to a report from Egor Homakov we take taken steps to foreclose people from spoofing Content-Types and getting data you weren't expecting onto your server.

Notation: Starting at version four.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 take either. Paperclip will enhance an error if you do not do this.

              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 practise non validate              do_not_validate_attachment_file_type              :avatar              end            

This keeps Paperclip secure-by-default, and will forestall people trying to mess with your filesystem.

NOTE: Too starting at version 4.0.0, Paperclip has some other validation that cannot be turned off. This validation will preclude content type spoofing. That is, uploading a PHP certificate (for case) as function of the EXIF tags of a well-formed JPEG. This check is limited to the media type (the showtime office of the MIME blazon, and then, 'text' in text/manifestly). This will forbid HTML documents from existence uploaded every bit JPEGs, but will not preclude GIFs from being uploaded with a .jpg extension. This validation will only add validation errors to the course. It will not crusade errors to be raised.

This can sometimes cause false validation errors in applications that employ custom file extensions. In these cases yous may wish to add your custom extension to the list of content type mappings by creating config/initializers/paperclip.rb:

              # Let ".foo" as an extension for files with the MIME type "text/plainly".              Paperclip              .              options              [              :content_type_mappings              ]              =              {              foo:              %w(              text/manifestly              )              }            

Defaults

Global defaults for all your Paperclip attachments tin can be defined by changing the Paperclip::Attachment.default_options Hash. This can exist useful for setting your default storage settings per case and then yous won't accept to ascertain them in every has_attached_file definition.

If you're using Rails, you lot tin can ascertain a Hash with default options in config/application.rb or in any of the config/environments/*.rb files on config.paperclip_defaults. These volition become merged into Paperclip::Attachment.default_options as your Rails app boots. An instance:

              module              YourApp              class              Application              <              Rails::Application              # Other code...              config              .              paperclip_defaults              =              {              storage:              :fog              ,              fog_credentials:              {              provider:              "Local"              ,              local_root:              "                  #{                  Rail                  .                  root                  }                /public"              }              ,              fog_directory:              ""              ,              fog_host:              "localhost"              }              end              stop            

Another option is to straight modify the Paperclip::Attachment.default_options Hash - this method works for non-Rails applications or is an choice if y'all prefer to identify the Paperclip default settings in an initializer.

An example Runway initializer would look something like this:

              Paperclip::Attachment              .              default_options              [              :storage              ]              =              :fog              Paperclip::Attachment              .              default_options              [              :fog_credentials              ]              =              {              provider:              "Local"              ,              local_root:              "                  #{                  Rail                  .                  root                  }                /public"              }              Paperclip::Attachment              .              default_options              [              :fog_directory              ]              =              ""              Paperclip::Attachment              .              default_options              [              :fog_host              ]              =              "http://localhost:3000"            

Migrations

Paperclip defines several migration methods which tin exist 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 zipper helper tin can be used when creating a table:

              class              CreateUsersWithAttachments              <              ActiveRecord::Migration              def              up              create_table              :users              practice              |t|              t              .              attachment              :avatar              end              end              # This is assuming yous are only using the users tabular array for Paperclip attachment. Drop with care!              def              down              drop_table              :users              end              end            

You tin can also use the alter method, instead of the up/downwardly combination above, as shown below:

              class              CreateUsersWithAttachments              <              ActiveRecord::Migration              def              modify              create_table              :users              do              |t|              t              .              attachment              :avatar              end              cease              end            

Schema Definition

Alternatively, the add_attachment and remove_attachment methods can exist used to add new Paperclip columns to an existing table:

              course              AddAttachmentColumnsToUsers              <              ActiveRecord::Migration              def              upwardly              add_attachment              :users              ,              :avatar              terminate              def              down              remove_attachment              :users              ,              :avatar              end              cease            

Or y'all tin can do this with the change method:

              class              AddAttachmentColumnsToUsers              <              ActiveRecord::Migration              def              modify              add_attachment              :users              ,              :avatar              stop              terminate            

Vintage Syntax

Vintage syntax (such as t.has_attached_file and drop_attached_file) is still supported in Paperclip 3.ten, but y'all're advised to update those migration files to apply this new syntax.


Storage

Paperclip ships with 3 storage adapters:

  • File Storage
  • S3 Storage (via aws-sdk-s3)
  • Fog Storage

If you lot would similar to utilise Paperclip with another storage, yous can install these gems along side with Paperclip:

  • paperclip-azure
  • paperclip-azure-storage
  • paperclip-dropbox

Agreement Storage

The files that are assigned as attachments are, by default, placed in the directory specified by the :path pick to has_attached_file. Past default, this location is :rails_root/public/arrangement/:class/:attachment/:id_partition/:mode/:filename. This location was called because, on standard Capistrano deployments, the public/organization directory tin can be symlinked to the app's shared directory, pregnant it survives between deployments. For example, using that :path, you may have a file at

              /information/myapp/releases/20081229172410/public/organisation/users/avatar/000/000/013/pocket-size/my_pic.png                          

NOTE: This is a alter from previous versions of Paperclip, merely is overall a safer choice for the default file store.

You may also cull to store your files using Amazon'southward S3 service. To do then, include the aws-sdk-s3 jewel in your Gemfile:

And and then you can specify using S3 from has_attached_file. You can observe more information about configuring and using S3 storage in the Paperclip::Storage::S3 documentation.

Files on the local filesystem (and in the Runway app's public directory) will exist available to the cyberspace at large. If you crave access control, it's possible to place your files in a different location. You will demand to change both the :path and :url options in social club 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 Rail' UploadedFile object to a StringIO to a Tempfile or even a simple String that is a URL that points to an image.

Paperclip volition accept, by default, many of these sources. It also is capable of treatment fifty-fifty more with a little configuration. The IO Adapters that handle images from non-local sources are non enabled by default. They tin can be enabled by adding a line like to the following into config/initializers/paperclip.rb:

              Paperclip::DataUriAdapter              .              register            

It'due south all-time to just enable a remote-loading adapter if you need it. Otherwise there's a hazard 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 example.
  • Paperclip::HttpUrlProxyAdapter - which accepts a http string.
  • Paperclip::DataUriAdapter - which accepts a Base64-encoded data: string.

Mail Processing

Paperclip supports an extensible selection of post-processors. When you ascertain a prepare of styles for an attachment, by default it is expected that those "styles" are really "thumbnails." These are processed past Paperclip::Thumbnail. For backward compatibility reasons you can pass either a single geometry string, or an assortment containing a geometry and a format that the file will exist converted to, similar and so:

              has_attached_file              :avatar              ,              styles:              {              thumb:              [              "32x32#"              ,              :png              ]              }            

This volition convert the "pollex" style to a 32x32 square in PNG format, regardless of what was uploaded. If the format is not specified, it is kept the aforementioned (e.g. JPGs will remain JPGs). Paperclip::Thumbnail uses ImageMagick to procedure images; ImageMagick's geometry documentation has more information on the accepted way formats.

For more than fine-grained control of the conversion procedure, source_file_options and convert_options tin can exist used to laissez passer flags and settings straight to ImageMagick's powerful Convert tool, documented here. For example:

              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 decision-making its resource limits. For example, you tin enforce memory or execution time limits by setting the post-obit variables in your awarding's process environs:

  • MAGICK_MEMORY_LIMIT=128MiB
  • MAGICK_MAP_LIMIT=64MiB
  • MAGICK_TIME_LIMIT=30

For a full listing of variables and clarification, see ImageMagick's resources documentation.


Custom Attachment Processors

You lot can write your own custom attachment processors to carry out tasks like adding watermarks, compressing images, or encrypting files. Custom processors must exist defined within the Paperclip module, inherit from Paperclip::Processor (see lib/paperclip/processor.rb), and implement a make method that returns a File. All files in your Rail app's lib/paperclip and lib/paperclip_processors directories will exist automatically loaded by Paperclip. Processors are specified using the :processors selection to has_attached_file:

              has_attached_file              :browse              ,              styles:              {              text:              {              quality:              :better              }              }              ,              processors:              [              :ocr              ]            

This would load the hypothetical grade Paperclip::Ocr, and laissez passer it the options hash { quality: :better }, along with the uploaded file.

Multiple processors can be specified, and they volition be invoked in the club they are divers in the :processors assortment. 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 case, assuming nosotros had this definition:

              has_attached_file              :browse              ,              styles:              {              text:              {              quality:              :better              }              }              ,              processors:              [              :rotator              ,              :ocr              ]            

Both the :rotator processor and the :ocr processor would receive the options { quality: :ameliorate }. If a processor receives an option information technology doesn't recognise, it's expected to ignore information technology.

Note: Considering processors operate past turning the original attachment into the styles, no processors will be run if there are no styles defined.

If you lot're interested in caching your thumbnail'south width, height and size in the database, take a look at the paperclip-meta gem.

Also, if you're interested in generating the thumbnail on-the-fly, y'all might want to look into the attachment_on_the_fly gem.

Paperclip's thumbnail generator (see 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 Mail Processing step, Paperclip calls dorsum to the model with a few callbacks, allowing the model to change or abolish the processing step. The callbacks are before_post_process and after_post_process (which are called before and subsequently the processing of each zipper), and the attachment-specific before_<zipper>_post_process and after_<zipper>_post_process. The callbacks are intended to exist as close to normal ActiveRecord callbacks equally possible, so if you return false (specifically - returning nil is not the same) in a before_filter, the post processing footstep volition halt. Returning fake in an after_filter volition not halt anything, but you can access the model and the attachment if necessary.

Note: Mail processing will not even commencement if the attachment is not valid co-ordinate to the validations. Your callbacks and processors volition only be called with valid attachments.

              class              Message              <              ActiveRecord::Base of operations              has_attached_file              :asset              ,              styles:              {              pollex:              "100x100#"              }              before_post_process              :skip_for_audio              def              skip_for_audio              !              %westward(              audio/ogg              awarding/ogg              )              .              include?              (              asset_content_type              )              end              end            

URI Obfuscation

Paperclip has an interpolation chosen :hash for obfuscating filenames of publicly-available files.

Example Usage:

              has_attached_file              :avatar              ,              {              url:              "/organization/:hash.:extension"              ,              hash_secret:              "longSecretString"              }            

The :hash interpolation will be replaced with a unique hash fabricated up of any 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 exist raised if :hash is used without :hash_secret present.

For more than on this feature, read the author's own explanation

Checksum / Fingerprint

A checksum of the original file assigned will be placed in the model if information technology has an attribute named fingerprint. Post-obit the user model migration example above, the migration would await like the following:

              class              AddAvatarFingerprintColumnToUser              <              ActiveRecord::Migration              def              upwards              add_column              :users              ,              :avatar_fingerprint              ,              :cord              finish              def              down              remove_column              :users              ,              :avatar_fingerprint              end              end            

The algorithm can exist specified using a configuration option; it defaults to MD5 for backwards compatibility with Paperclip 5 and before.

              has_attached_file              :some_attachment              ,              adapter_options:              {              hash_digest:              Digest::SHA256              }            

Run CLASS=User ATTACHMENT=avatar rake paperclip:refresh:fingerprints later 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 lodge to play nicely with soft-deleted models. (acts_as_paranoid, paranoia, etc.)

              has_attached_file              :some_attachment              ,              {              preserve_files:              true              ,              }            

This will prevent some_attachment from beingness wiped out when the model gets destroyed, so information technology volition still exist when the object is restored later.


Dynamic Configuration

Callable objects (lambdas, Procs) can exist 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 office of the user. Perhaps some users are bosses (due east.chiliad. a User model instance responds to #boss?) and merit a bigger avatar thumbnail than regular users. The configuration to determine what way parameters are to be used based on the user part might wait as follows where a boss will receive a 300x300 thumbnail otherwise a 100x100 thumbnail will be created.

              course              User              <              ActiveRecord::Base of operations              has_attached_file              :avatar              ,              styles:              lambda              {              |attachment|              {              thumb:              (              attachment              .              case              .              boss?              ?              "300x300>"              :              "100x100>"              )              }              }              end            

Dynamic Processors:

Another contrived example is a user model that is aware of which file processors should be applied to information technology (across the implied thumbnail processor invoked when :styles are divers). Possibly we take a watermark processor bachelor and information technology is only used on the avatars of certain models. The configuration for this might exist where the example is queried for which processors should exist applied to information technology. Presumably some users might return [:thumbnail, :watermark] for its processors, where a divers watermark processor is invoked after the thumbnail processor already divers by Paperclip.

              course              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 (east.grand. during testing) add together this into your surroundings's configuration:

              Your::Application              .              configure              practice              ...              Paperclip              .              options              [              :log              ]              =              imitation              ...              end            

More than information in the rdocs


Deployment

To make Capistrano symlink the public/arrangement directory so that attachments survive new deployments, set the linked_dirs option in your config/deploy.rb file:

              set up              :linked_dirs              ,              fetch              (              :linked_dirs              ,              [              ]              )              .              push button              (              'public/organization'              )            

Attachment Styles

Paperclip is aware of new attachment styles yous have added in previous deploys. The only thing yous should do subsequently each deployment is to call rake paperclip:refresh:missing_styles. It will store current attachment styles in RAILS_ROOT/public/organization/paperclip_attachments.yml past default. You lot can change it by:

              Paperclip              .              registered_attachments_styles_path              =              '/tmp/config/paperclip_attachments.yml'            

Here is an example for Capistrano:

              namespace              :paperclip              exercise              desc              "build missing paperclip styles"              chore              :build_missing_styles              practice              on              roles              (              :app              )              practice              within              release_path              practice              with              rails_env:              fetch              (              :rails_env              )              exercise              execute              :rake              ,              "paperclip:refresh:missing_styles"              terminate              end              end              end              end              after              (              "deploy:compile_assets"              ,              "paperclip:build_missing_styles"              )            

At present yous don't have to remember to refresh thumbnails in production every fourth dimension you add a new way. Unfortunately, it does not work with dynamic styles - it simply ignores them.

If you already have a working app and don't want rake paperclip:refresh:missing_styles to refresh onetime pictures, you need to tell Paperclip about existing styles. Simply create a paperclip_attachments.yml file by manus. For example:

              form              User              <              ActiveRecord::Base              has_attached_file              :avatar              ,              styles:              {              thumb:              'x100'              ,              croppable:              '600x600>'              ,              large:              '1000x1000>'              }              finish              class              Volume              <              ActiveRecord::Base of operations              has_attached_file              :cover              ,              styles:              {              modest:              'x100'              ,              large:              '1000x1000>'              }              has_attached_file              :sample              ,              styles:              {              thumb:              'x100'              }              stop            

So in RAILS_ROOT/public/arrangement/paperclip_attachments.yml:

---              :User:              :avatar:   -              :thumb              -              :croppable              -              :large              :Book:              :cover:   -              :small              -              :large              :sample:   -              :thumb            

Testing

Paperclip provides rspec-compatible matchers for testing attachments. Run into the documentation on Paperclip::Shoulda::Matchers for more data.

Parallel Tests

Because of the default path for Paperclip storage, if you try to run tests in parallel, yous may detect that files go overwritten considering the same path is being calculated for them in each test process. While this set works for parallel_tests, a like concept should be used for whatsoever other mechanism for running tests meantime.

              if              ENV              [              'PARALLEL_TEST_GROUPS'              ]              Paperclip::Zipper              .              default_options              [              :path              ]              =              ":rails_root/public/system/:rails_env/                  #{                  ENV                  [                  'TEST_ENV_NUMBER'                  ]                  .                  to_i                  }                /:class/:zipper/:id_partition/:filename"              else              Paperclip::Attachment              .              default_options              [              :path              ]              =              ":rails_root/public/system/:rails_env/:class/:attachment/:id_partition/:filename"              stop            

The important part here beingness the inclusion of ENV['TEST_ENV_NUMBER'], or a similar machinery for whichever parallel testing library you lot apply.

Integration Tests

Using integration tests with FactoryBot may save multiple copies of your examination files within the app. To avert this, specify a custom path in the config/environments/exam.rb like so:

              Paperclip::Zipper              .              default_options              [              :path              ]              =              "                  #{                  Track                  .                  root                  }                /spec/test_files/:grade/:id_partition/:style.:extension"            

Then, make certain to delete that directory later the test suite runs by adding this to spec_helper.rb.

              config              .              later              (              :suite              )              do              FileUtils              .              rm_rf              (              Dir              [              "                  #{                  Rails                  .                  root                  }                /spec/test_files/"              ]              )              stop            

Example of test configuration with Factory Bot

              FactoryBot              .              define              do              factory              :user              do              avatar              {              File              .              new              (              "                  #{                  Rails                  .                  root                  }                /spec/support/fixtures/image.jpg"              )              }              finish              end            

Contributing

If you'd similar to contribute a feature or bugfix: Thank you! To brand certain your ready/feature has a loftier run a risk of existence included, please read the post-obit guidelines:

  1. Mail a pull asking.
  2. Make certain there are tests! Nosotros will not accept any patch that is not tested. Information technology'due south a rare time when explicit tests aren't needed. If you take questions about writing tests for paperclip, please open up a GitHub issue.

Delight see CONTRIBUTING.md for more than details on contributing and running examination.

Cheers to all the contributors!

License

Paperclip is Copyright © 2008-2017 thoughtbot, inc. Information technology is free software, and may be redistributed nether the terms specified in the MIT-LICENSE file.

About thoughtbot

thoughtbot

Paperclip is maintained and funded by thoughtbot. The names and logos for thoughtbot are trademarks of thoughtbot, inc.

We honey open source software! See our other projects or hire u.s. to design, develop, and grow your product.

kahnadjoich66.blogspot.com

Source: https://github.com/thoughtbot/paperclip

Post a Comment for "Ruby Upload File and State at Same Page"