### Basic Setup and Test Execution Source: https://github.com/thoughtbot/paperclip/blob/main/CONTRIBUTING.md Initial setup steps including bundle installation and running the project's tests using Rake. ```bash bundle && bundle exec rake ``` -------------------------------- ### Controller Action for User Creation Source: https://github.com/thoughtbot/paperclip/wiki/Quick-Start A basic controller action to create a new user record, typically receiving the user parameters from the request. ```ruby def create @user = User.create( params[:user] ) end ``` -------------------------------- ### Paperclip User Model Example Source: https://github.com/thoughtbot/paperclip/blob/main/MIGRATING.md Demonstrates a typical Paperclip model setup for handling file attachments. ```ruby class User < ApplicationRecord has_attached_file :avatar end ``` -------------------------------- ### Displaying Attached Images Source: https://github.com/thoughtbot/paperclip/wiki/Quick-Start Shows how to display an attached image using the `image_tag` helper, including default and styled versions of the attachment. ```rhtml <%= image_tag @user.avatar.url %> <%= image_tag @user.avatar.url(:medium) %> <%= image_tag @user.avatar.url(:thumb) %> ``` -------------------------------- ### Paperclip User Model Example Source: https://github.com/thoughtbot/paperclip/blob/main/MIGRATING-ES.md Demonstrates a typical Paperclip model setup in Rails, showing how to attach files using `has_attached_file`. ```ruby class User < ApplicationRecord has_attached_file :avatar end ``` -------------------------------- ### Install ImageMagick Dependencies on OSX Source: https://github.com/thoughtbot/paperclip/wiki/How-to-fix-NoMethodError-after-ImageMagick-Update-(OSX-Homebrew) Installs essential optional dependencies for ImageMagick on OSX using Homebrew. These libraries enhance ImageMagick's capabilities and resolve potential compatibility issues. ```bash brew install fontconfig libtiff little-cms2 jasper libwmf librsvg liblqr openexr ghostscript webp ``` -------------------------------- ### Bundler Setup and Version Check Source: https://github.com/thoughtbot/paperclip/blob/main/features/support/fixtures/preinitializer.txt This snippet demonstrates the initial setup for the Paperclip project using RubyGems and Bundler. It includes error handling for missing Bundler, checks for the Bundler version compatibility with Rails 2.3, and sets up the BUNDLE_GEMFILE environment variable. It also handles potential `Bundler::GemNotFound` errors. ```ruby begin require "rubygems" require "bundler" rescue LoadError raise "Could not load the bundler gem. Install it with `gem install bundler`." end if Gem::Version.new(Bundler::VERSION) <= Gem::Version.new("0.9.24") raise RuntimeError, "Your bundler version is too old for Rails 2.3." "Run `gem install bundler` to upgrade." end begin # Set up load paths for all bundled gems ENV["BUNDLE_GEMFILE"] = File.expand_path("../../Gemfile", __FILE__) Bundler.setup rescue Bundler::GemNotFound raise RuntimeError, "Bundler couldn't find some gems." "Did you run `bundle install`?" end ``` -------------------------------- ### Install ActiveStorage Source: https://github.com/thoughtbot/paperclip/blob/main/MIGRATING.md Command to install ActiveStorage, which includes generating necessary migrations. ```sh rails active_storage:install ``` -------------------------------- ### Install Paperclip Gem Source: https://github.com/thoughtbot/paperclip/wiki/Installation Instructions for adding the Paperclip gem to your application's Gemfile. Supports specific versions, older Rails versions, and direct Git installation from the master branch. ```ruby gem "paperclip", "~> 3.1" ``` ```ruby gem "paperclip", "~> 2.7" ``` ```ruby gem "paperclip", :git => "git://github.com/thoughtbot/paperclip.git" ``` -------------------------------- ### Add Attachment Columns Migration Source: https://github.com/thoughtbot/paperclip/wiki/Quick-Start A database migration to add the necessary columns for a file attachment (e.g., 'avatar') to a table (e.g., 'users'). Includes methods for both up and down migrations. ```ruby class AddAvatarColumnsToUsers < ActiveRecord::Migration def self.up add_attachment :users, :avatar end def self.down remove_attachment :users, :avatar end end ``` -------------------------------- ### Define Attached File in Model Source: https://github.com/thoughtbot/paperclip/wiki/Quick-Start Configures a file attachment named 'avatar' in an ActiveRecord model, specifying different styles for the attached file. ```ruby class User < ActiveRecord::Base attr_accessible :avatar has_attached_file :avatar, :styles => { :medium => "300x300>", :thumb => "100x100>" } end ``` -------------------------------- ### Install Dependencies and Run Tests Source: https://github.com/thoughtbot/paperclip/blob/main/CONTRIBUTING.md Installs all necessary gems for testing against multiple Rails versions using Appraisal and then executes the full test suite. ```bash bundle install bundle exec appraisal install bundle exec appraisal rake ``` -------------------------------- ### Detaching a File Source: https://github.com/thoughtbot/paperclip/wiki/Quick-Start Demonstrates how to remove or detach an attached file from a model instance by setting the attachment attribute to nil and saving the record. ```ruby @user.avatar = nil @user.save ``` -------------------------------- ### File Upload Form Field Source: https://github.com/thoughtbot/paperclip/wiki/Quick-Start Renders a file input field for an attachment within a form, ensuring the form has the correct `multipart` option for file uploads. ```rhtml <%= form_for @user, :url => users_path, :html => { :multipart => true } do |form| %> <%= form.file_field :avatar %> <% end %> ``` -------------------------------- ### Re-install ImageMagick using Homebrew Source: https://github.com/thoughtbot/paperclip/wiki/How-to-fix-NoMethodError-after-ImageMagick-Update-(OSX-Homebrew) Installs ImageMagick on your OSX system using Homebrew after ensuring all necessary dependencies are in place. This step typically resolves the Dyld library loading errors. ```bash brew install imagemagick ``` -------------------------------- ### Install ImageMagick with apt-get (Debian/Ubuntu) Source: https://github.com/thoughtbot/paperclip/blob/main/README.md Installs ImageMagick using the apt-get package manager on Debian-based Linux distributions like Ubuntu. ```bash sudo apt-get install imagemagick -y ``` -------------------------------- ### Install ActiveStorage Migrations Source: https://github.com/thoughtbot/paperclip/blob/main/MIGRATING-ES.md This command generates the necessary ActiveStorage database tables. Ensure you have the `mini_magick` gem in your Gemfile for image processing. ```sh rails active_storage:install ``` -------------------------------- ### Install Ghostscript with Homebrew (macOS) Source: https://github.com/thoughtbot/paperclip/blob/main/README.md Installs Ghostscript using Homebrew on macOS, which is required for handling PDF uploads and running Paperclip's test suite. ```bash brew install gs ``` -------------------------------- ### Install ImageMagick with Homebrew (macOS) Source: https://github.com/thoughtbot/paperclip/blob/main/README.md Installs ImageMagick using the Homebrew package manager on macOS, a prerequisite for Paperclip's image processing capabilities. ```bash brew install imagemagick ``` -------------------------------- ### Install GhostScript with Homebrew Source: https://github.com/thoughtbot/paperclip/wiki/Requirements Installs GhostScript using the Homebrew package manager on macOS. GhostScript is required for handling PDF uploads and running the Paperclip test suite. ```shell brew install gs ``` -------------------------------- ### Paperclip Gem Installation Source: https://github.com/thoughtbot/paperclip/blob/main/README.md Instructions for including the Paperclip gem in your Rails application's Gemfile, including options for specifying a version or the master branch. ```ruby gem "paperclip", "~> 6.0.0" ``` ```ruby gem "paperclip", git: "git://github.com/thoughtbot/paperclip.git" ``` -------------------------------- ### Unix file command requirement Source: https://github.com/thoughtbot/paperclip/blob/main/README.md Details the requirement for the Unix `file` command for content-type checking in Paperclip and provides manual installation instructions for Windows. ```bash # Ensure the file command is in your system's PATH or configure Paperclip: # Paperclip.options[:command_path] = 'C:\\Program Files (x86)\\GnuWin32\\bin' ``` -------------------------------- ### Paperclip View Helpers for Images Source: https://github.com/thoughtbot/paperclip/blob/main/README.md Examples of using Paperclip's view helpers to display attached images in different styles. ```erb <%= image_tag @user.avatar.url %> <%= image_tag @user.avatar.url(:medium) %> <%= image_tag @user.avatar.url(:thumb) %> ``` -------------------------------- ### FactoryBot Example for Paperclip Attachment Source: https://github.com/thoughtbot/paperclip/blob/main/README.md Illustrates how to define a FactoryBot factory for a model with a Paperclip attachment. It shows how to associate a file fixture with the attachment attribute. ```ruby FactoryBot.define do factory :user do avatar { File.new("#{Rails.root}/spec/support/fixtures/image.jpg") } end end ``` -------------------------------- ### Paperclip Model Configuration Source: https://github.com/thoughtbot/paperclip/blob/main/README.md Example of configuring Paperclip in a Rails model, including defining attachment styles and a default URL. ```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 ``` -------------------------------- ### Remove ImageMagick using Homebrew Source: https://github.com/thoughtbot/paperclip/wiki/How-to-fix-NoMethodError-after-ImageMagick-Update-(OSX-Homebrew) This command removes the ImageMagick package and its associated configuration files from your system using Homebrew. ```bash brew remove --purge imagemagick ``` -------------------------------- ### Install ImageMagick with Homebrew Source: https://github.com/thoughtbot/paperclip/wiki/Requirements Installs ImageMagick using the Homebrew package manager on macOS. ImageMagick is required for image processing by Paperclip. ```shell brew install imagemagick ``` -------------------------------- ### Form for File Upload (Standard Rails) Source: https://github.com/thoughtbot/paperclip/blob/main/README.md Example of a Rails form helper for uploading files using Paperclip. ```erb <%= form_for @user, url: users_path, html: { multipart: true } do |form| <%= form.file_field :avatar %> <%= form.submit %> <% end %> ``` -------------------------------- ### Paperclip API: Configuration Options Source: https://github.com/thoughtbot/paperclip/wiki/Upgrade-Paperclip-4x-to-5x This section details key configuration options for Paperclip when integrating with AWS S3, particularly for aws-sdk v2 compatibility. ```APIDOC Paperclip Configuration: Paperclip.options[:s3_region] = 'your-s3-region' - Sets the AWS S3 region for all Paperclip S3 operations. - Required for aws-sdk v2. Paperclip.options[:s3_permissions] = 'public-read' - Sets the default permissions for uploaded files. - Format changed from underscore to hyphen (e.g., :public_read -> 'public-read'). Paperclip.options[:s3_server_side_encryption] = 'AES256' - Specifies the server-side encryption method for S3 uploads. - The value 'AES256' (string) is now required, replacing the symbol :aes256. ``` -------------------------------- ### Gemfile Setup for MP3 Metadata Source: https://github.com/thoughtbot/paperclip/wiki/Extracting-mp3-metadata This snippet shows how to add the ruby-mp3info gem to your Gemfile, which is necessary for extracting MP3 metadata using Paperclip. ```ruby gem 'ruby-mp3info', :require => 'mp3info' ``` -------------------------------- ### Form for File Upload (Simple Form) Source: https://github.com/thoughtbot/paperclip/blob/main/README.md Example of a form for file uploads using the Simple Form gem with Paperclip. ```erb <%= simple_form_for @user, url: users_path do |form| <%= form.input :avatar, as: :file %> <%= form.submit %> <% end %> ``` -------------------------------- ### Access Token Generation and Interpolation Source: https://github.com/thoughtbot/paperclip/wiki/Interpolations Provides methods for generating a SHA1-hashed access token and defines the Paperclip interpolation to use this token in file paths. It includes helper methods for salt generation and token creation, triggered before saving a record. ```ruby before_create :generate_access_token private # simple random salt def random_salt(len = 20) chars = ("a".."z").to_a + ("A".."Z").to_a + ("0".."9").to_a salt = "" 1.upto(len) { |i| salt << chars[rand(chars.size-1)] } return salt end # SHA1 from random salt and time def generate_access_token self.access_token = Digest::SHA1.hexdigest("#{random_salt}#{Time.now.to_i}") end # interpolate in paperclip Paperclip.interpolates :access_token do |attachment, style| attachment.instance.access_token end ``` -------------------------------- ### Paperclip::Glue Module for Non-Rails Models Source: https://github.com/thoughtbot/paperclip/wiki/Installation Demonstrates how to include the `Paperclip::Glue` module in models for non-Rails applications to enable Paperclip functionality. This is automatically handled by Rails. ```APIDOC ModuleName: include Paperclip::Glue # ... other model configurations ``` -------------------------------- ### Paperclip Attachment with Access Token Interpolation Source: https://github.com/thoughtbot/paperclip/wiki/Interpolations Configures a Paperclip attachment (`foto`) with a custom URL and path that uses an `access_token` interpolation. It also defines styles and default settings. ```ruby has_attached_file :foto, :default_url => '/images/foto.jpg', :default_style => :medium, :use_timestamp => false, :url => '/system/:access_token/foto_:style.:extension', :path => ':rails_root/public:url', :styles => { :medium => "470x320", :small => "162x107" } ``` -------------------------------- ### Rails Bootstrapping with Paperclip Source: https://github.com/thoughtbot/paperclip/blob/main/features/support/fixtures/boot_config.txt This snippet demonstrates the bootstrapping process for a Rails application when using the Paperclip gem. It shows how the initializer loads dependencies and sets up the environment. ```ruby class Rails::Boot def run load_initializer Rails::Initializer.class_eval do def load_gems @bundler_loaded ||= Bundler.require :default, Rails.env end end Rails::Initializer.run(:set_load_path) end end Rails.boot! ``` -------------------------------- ### Running Paperclip Tests Source: https://github.com/thoughtbot/paperclip/wiki/Contribution-Guidelines Commands to bootstrap and run the Paperclip test suite against multiple Ruby on Rails versions using Appraisal. ```bash bundle install bundle exec rake appraisal:install ``` ```bash bundle exec rake ``` ```bash BUNDLE_GEMFILE=gemfiles/3.2.gemfile ruby -Itest test/schema_test.rb ``` ```bash BUNDLE_GEMFILE=gemfiles/3.2.gemfile cucumber features/basic_integration.feature ``` -------------------------------- ### Paperclip Permissions Format Update Source: https://github.com/thoughtbot/paperclip/wiki/Upgrade-Paperclip-4x-to-5x In aws-sdk v2, Paperclip's permission formats have been updated. For example, `:public_read` should now be specified as `'public-read'`. ```ruby has_attached_file :avatar, styles: { medium: "300x300>", thumb: "100x100>" }, storage: :s3, s3_region: ENV['AWS_REGION'], s3_permissions: 'public-read' ``` -------------------------------- ### Build and Push Gem Source: https://github.com/thoughtbot/paperclip/blob/main/RELEASING.md Commands to build the paperclip gem and push it to a gem repository. ```bash gem build paperclip.gemspec gem push paperclip-VERSION.gem ``` -------------------------------- ### Paperclip vs. ActiveStorage View Helpers Source: https://github.com/thoughtbot/paperclip/blob/main/MIGRATING-ES.md Illustrates the difference in how attachments are referenced in views between Paperclip and ActiveStorage. Paperclip uses URL helpers, while ActiveStorage uses variant transformations for resizing and other processing. ```html image_tag @user.avatar.url(:medium) image_tag @user.avatar.variant(resize: "250x250") ``` -------------------------------- ### Using Processors with Paperclip Source: https://github.com/thoughtbot/paperclip/blob/main/README.md Demonstrates how to define and use custom processors with Paperclip attachments. Processors are invoked in the order they are defined and receive options from the styles hash. If a processor doesn't recognize an option, it should ignore it. Post processing is skipped if no styles are defined. ```ruby has_attached_file :scan, styles: { text: { quality: :better } }, processors: [:ocr] ``` ```ruby has_attached_file :scan, styles: { text: { quality: :better } }, processors: [:rotator, :ocr] ``` -------------------------------- ### View Helper Update for Image Tagging Source: https://github.com/thoughtbot/paperclip/blob/main/MIGRATING.md Shows the change in view helpers for displaying images. Paperclip used `.url(:size)`, while Active Storage uses `.variant(resize: "WxH")` to specify image transformations. ```ruby image_tag @user.avatar.url(:medium) ``` ```ruby image_tag @user.avatar.variant(resize: "250x250") ``` -------------------------------- ### Content Type Validation for Images Source: https://github.com/thoughtbot/paperclip/blob/main/README.md Restrict allowed content types to prevent security vulnerabilities like XSS attacks. This example allows only common image types. ```ruby validates_attachment :avatar, content_type: ["image/jpeg", "image/gif", "image/png"] ``` -------------------------------- ### Define Attachment with Hashing Source: https://github.com/thoughtbot/paperclip/wiki/Hashing Example of defining an attachment in a Rails model after configuring Paperclip defaults for hashing. No modifications are needed for the attachment definition itself. ```ruby class Profile has_attached_file :portrait end ``` -------------------------------- ### Heroku Buildpack Configuration for ImageMagick Source: https://github.com/thoughtbot/paperclip/wiki/Upgrade-Imagemagick-On-Heroku This snippet demonstrates the Heroku CLI commands required to set the Ruby buildpack and add the ImageMagick buildpack at the specified index for your Heroku application. ```bash heroku buildpacks:set https://github.com/heroku/heroku-buildpack-ruby heroku buildpacks:add --index 1 https://github.com/ello/heroku-buildpack-imagemagick ``` -------------------------------- ### Security Validations (Required from v4.0.0) Source: https://github.com/thoughtbot/paperclip/blob/main/README.md Starting from version 4.0.0, Paperclip requires explicit validation for content type, file name, or a declaration to skip validation. This enhances security. ```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 ``` -------------------------------- ### Paperclip User Table Schema Source: https://github.com/thoughtbot/paperclip/blob/main/MIGRATING.md Illustrates the database table structure created by Paperclip for storing avatar metadata. ```ruby create_table "users", force: :cascade do |t| t.string "avatar_file_name" t.string "avatar_content_type" t.integer "avatar_file_size" t.datetime "avatar_updated_at" end ``` -------------------------------- ### Custom Category Name Interpolation Source: https://github.com/thoughtbot/paperclip/wiki/Interpolations Defines a custom interpolation to include a category name in the attachment URL. This requires the model to have a `category` attribute with a `name` method. ```ruby Paperclip.interpolates :category_name do |attachment, style| attachment.instance.category.name end ``` -------------------------------- ### Configure Paperclip Attachment Styles Path Source: https://github.com/thoughtbot/paperclip/blob/main/README.md Demonstrates how to change the default path for storing Paperclip attachment styles configuration. This is useful for custom deployment setups or specific file system requirements. ```ruby Paperclip.registered_attachments_styles_path = '/tmp/config/paperclip_attachments.yml' ``` -------------------------------- ### Configure Paperclip Hashing Defaults Source: https://github.com/thoughtbot/paperclip/wiki/Hashing An initializer script to update Paperclip's default options, enabling secure attachment hashing by specifying the URL pattern and hash secret. ```ruby # config/initializers/paperclip_defaults.rb Paperclip::Attachment.default_options.update({ url: "/system/:class/:attachment/:id_partition/:style/:hash.:extension", hash_secret: Rails.application.secrets.secret_key_base }) ``` -------------------------------- ### Run Specific Tests with Bundled Gemfile Source: https://github.com/thoughtbot/paperclip/blob/main/CONTRIBUTING.md Demonstrates how to run specific RSpec or Cucumber tests by setting the BUNDLE_GEMFILE environment variable to target a particular Rails version's gemfile. ```bash BUNDLE_GEMFILE=gemfiles/4.1.gemfile rspec spec/paperclip/attachment_spec.rb BUNDLE_GEMFILE=gemfiles/4.1.gemfile cucumber features/basic_integration.feature ``` -------------------------------- ### Paperclip Asset Model Configuration Source: https://github.com/thoughtbot/paperclip/wiki/Conditionally-resizing-images Configures an asset model with Paperclip to handle file uploads, define styles for attachments, and conditionally process images before post-processing. ```ruby class Asset < ActiveRecord::Base has_attached_file :upload, :styles => {:thumb => '100x100#'} before_post_process :resize_images def image? upload_content_type =~ %r{^(image|(x-)?application)/(bmp|gif|jpeg|jpg|pjpeg|png|x-png)}$} end private def resize_images return false unless image? end end ``` -------------------------------- ### Configure Paperclip Command Path Source: https://github.com/thoughtbot/paperclip/wiki/Requirements Sets the directory where Paperclip can find ImageMagick utilities. This is typically configured in the development environment's Rails initializer. ```ruby Paperclip.options[:command_path] = "/usr/local/bin/" ``` -------------------------------- ### Paperclip 4.x Attachment Validation Requirement Source: https://github.com/thoughtbot/paperclip/wiki/Upgrade-Paperclip-3x-to-4x Starting with Paperclip version 4.0, attachments must include a content_type validation, a file_name validation, or explicitly state they will not have either. Failure to comply will result in a Paperclip::Errors::MissingRequiredValidatorError. ```ruby class AttachmentModel < ApplicationRecord has_attached_file :attachment # Option 1: Content Type Validation validates_attachment_content_type :attachment, content_type: ['image/jpeg', 'image/png'] # Option 2: File Name Validation # validates_attachment_file_name :attachment, matches: [/pngZ/, /jpe?gZ/] # Option 3: Explicitly state no validation (use with caution) # has_attached_file :attachment, validate_missing_attachment_validators: false end ``` -------------------------------- ### Model Validation Update with file_validators Gem Source: https://github.com/thoughtbot/paperclip/blob/main/MIGRATING.md Shows how to migrate Paperclip's built-in attachment validations to use the `file_validators` gem. This example demonstrates validating content type and file name using the gem's syntax. ```diff class User < ApplicationRecord # ... - validates_attachment_content_type :avatar, content_type: /\Aimage/ - validates_attachment_file_name :avatar, matches: /jpe?g\z/ + validates :avatar, file_content_type: { + allow: ["image/jpeg", "image/png"], + if: -> { avatar.attached? }, + } + validates :avatar, file_name: { matches: /\.(jpg|png)\z/, if: -> { avatar.attached? } } ``` -------------------------------- ### Controller Optimization with `includes` Source: https://github.com/thoughtbot/paperclip/blob/main/MIGRATING-ES.md Demonstrates how to prevent N+1 query problems in controllers when dealing with attached files. By using `includes(:avatar_attachment)`, the application eager-loads the attachment associations, reducing the number of database queries. ```ruby # Without optimization (potential N+1) def index @users = User.all.order(:name) end # With optimization def index @users = User.all.order(:name).includes(:avatar_attachment) end ``` -------------------------------- ### Paperclip S3 Server-Side Encryption Update Source: https://github.com/thoughtbot/paperclip/wiki/Upgrade-Paperclip-4x-to-5x AWS no longer supports `:aes256` for server-side encryption with S3. The value must now be the string "AES256" to avoid `Aws::S3::Errors::InvalidArgument`. ```ruby has_attached_file :attachment, styles: { thumb: "100x100#" }, storage: :s3, s3_credentials: Rails.root.join("config", "s3.yml"), path: ":attachment_basename/:id/:style/:filename", s3_server_side_encryption: "AES256" ``` -------------------------------- ### Paperclip S3 Configuration Changes for aws-sdk v2 Source: https://github.com/thoughtbot/paperclip/wiki/Upgrade-Paperclip-4x-to-5x When using Paperclip with S3 storage and aws-sdk version 2.0.0 or later, you need to configure the S3 region. Permissions formats have also changed from underscore to hyphen. ```ruby config.paperclip_defaults.merge!( s3_region: 'your-s3-region' ) ``` -------------------------------- ### Paperclip Default Options Source: https://github.com/thoughtbot/paperclip/wiki/Hashing Displays the default options for Paperclip's attachment path and URL generation, including hashing-related configurations. ```ruby Paperclip::Attachment.default_options # => { # :hash_data=>":class/:attachment/:id/:style/:updated_at", # :hash_digest=>"SHA1", # :path=>":rails_root/public:url", # :url=>"/system/:class/:attachment/:id_partition/:style/:filename", # } ``` -------------------------------- ### FactoryBot Update for File Attachments Source: https://github.com/thoughtbot/paperclip/blob/main/MIGRATING.md Demonstrates how to update FactoryBot definitions to use `ActiveSupport::Testing::FixtureFiles#file_fixture` for attaching files, replacing direct assignment of Paperclip attributes. This involves using `transient` attributes and an `after :build` hook. ```diff factory :user do trait :with_avatar do - avatar_file_name { "avatar.jpg" } - avatar_file_type { "image/jpg" } - avatar_file_size { 1024 } + transient do + avatar_file { file_fixture("avatar.jpg") } + + after :build do |user, evaluator| + user.avatar.attach( + io: evaluator.avatar_file.open, + filename: evaluator.avatar_file.basename.to_s, + ) + end + end end end ``` -------------------------------- ### File Existence Checks in Paperclip Source: https://github.com/thoughtbot/paperclip/blob/main/README.md Explains the difference between `file?`/`present?` and `exists?` for checking file presence with Paperclip, highlighting performance implications. ```APIDOC File Existence Checks: - `file?` and `present?`: Checks if the `_file_name` field is populated. This is performant. - `exists?`: Checks if the file actually exists on the storage. This may perform a network request if stored remotely (e.g., S3). Usage Note: Prefer `file?` or `present?` for simple presence checks, especially in loops, to avoid unnecessary network I/O. ``` -------------------------------- ### Paperclip Model Configuration for MP3s Source: https://github.com/thoughtbot/paperclip/wiki/Extracting-mp3-metadata This Ruby code demonstrates how to configure a Paperclip model to handle file uploads, extract MP3 metadata, and define helper methods for audio file identification and display name generation. ```ruby # Table name: assets # # id :integer(4) not null, primary key # upload_file_name :string(255) not null # upload_content_type :string(255) # upload_file_size :integer(4) not null # upload_updated_at :datetime # metadata :text has_attached_file :upload before_save :extract_metadata serialize :metadata # Helper method to determine whether or not an attachment is an mp3 file. # @note Use only if you have a generic asset-type model that can handle different file types. def audio? upload_content_type =~ %r{^audio/(?:mp3|mpeg|mpeg3|mpg|x-mp3|x-mpeg|x-mpeg3|x-mpegaudio|x-mpg$)} end # MP3-aware display name, consisting of track title and artist # Force encoding required to deal with mixed content bugs on Ruby 1.9 # @return 'Title - Artist' if audio file # @return 'file.ext' if not audio file def display_name @display_name ||= if audio? && metadata? artist, title = metadata.values_at('artist', 'title') title.present? ? [title, artist].compact.join(' - ').force_encoding('UTF-8') : upload_file_name else upload_file_name end end private # Retrieves metadata for MP3s def extract_metadata return unless audio? path = upload.queued_for_write[:original].path open_opts = { :encoding => 'utf-8' } Mp3Info.open(path, open_opts) do |mp3info| self.metadata = mp3info.tag end end ``` -------------------------------- ### Paperclip Path Configuration for Integration Tests with FactoryBot Source: https://github.com/thoughtbot/paperclip/blob/main/README.md Sets a custom Paperclip attachment path for integration tests using FactoryBot. This helps manage test files and prevent duplication. It also includes a cleanup step in `spec_helper.rb` to remove the test files directory after the suite runs. ```ruby Paperclip::Attachment.default_options[:path] = "#{Rails.root}/spec/test_files/:class/:id_partition/:style.:extension" # In spec_helper.rb config.after(:suite) do FileUtils.rm_rf(Dir["#{Rails.root}/spec/test_files/"]) end ``` -------------------------------- ### Moving Local Storage Files for ActiveStorage Migration Source: https://github.com/thoughtbot/paperclip/blob/main/MIGRATING.md This script iterates through ActiveStorage attachments, determines the source path from the old Paperclip attachment, and copies the file to the new ActiveStorage directory structure. It creates the necessary directories and prints the move operation. ```ruby #!/bin/rails runner ActiveStorage::Attachment.find_each do |attachment| name = attachment.name source = attachment.record.send(name).path dest_dir = File.join( "storage", attachment.blob.key.first(2), attachment.blob.key.first(4).last(2)) dest = File.join(dest_dir, attachment.blob.key) FileUtils.mkdir_p(dest_dir) puts "Moving #{source} to #{dest}" FileUtils.cp(source, dest) end ``` -------------------------------- ### Controller Action for Paperclip Upload Source: https://github.com/thoughtbot/paperclip/blob/main/README.md Controller code to handle the creation of a record with a Paperclip attachment, including strong parameters. ```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 ``` -------------------------------- ### Paperclip Default Configuration for Minio Source: https://github.com/thoughtbot/paperclip/wiki/Paperclip-with-minio Sets the default configuration for Paperclip to use Minio object storage. This includes storage type, S3 protocol, permissions, region, credentials, host name, and specific options for the aws-sdk, such as endpoint and force_path_style. ```ruby config.paperclip_defaults = { storage: :s3, s3_protocol: ':https', s3_permissions: 'private', s3_region: 'us-east-1', s3_credentials: { bucket: 'testbucket', access_key_id: 'Q3AM3UQ867SPQQA43P2F', secret_access_key: 'zuf+tfteSlswRu7BJ86wekitnifILbZam1KYY3TG', }, s3_host_name: 'play.minio.io:9000', s3_options: { endpoint: "https://play.minio.io:9000", # for aws-sdk force_path_style: true # for aws-sdk (required for minio) }, url: ':s3_path_url' } ``` -------------------------------- ### Paperclip Configuration for ImageMagick Path Source: https://github.com/thoughtbot/paperclip/blob/main/README.md Configures the path to the ImageMagick command-line utilities, which Paperclip uses for image processing. This is typically set in the Rails environment configuration file. ```ruby Paperclip.options[:command_path] = "/usr/local/bin/" ``` -------------------------------- ### Advanced ImageMagick Options for Styles Source: https://github.com/thoughtbot/paperclip/blob/main/README.md For more control over image processing, Paperclip allows passing specific options to ImageMagick's Convert tool using `source_file_options` and `convert_options`. These options can fine-tune aspects like density, depth, quality, and apply effects like posterization. ```ruby has_attached_file :image, styles: { regular: ['800x800>', :png] }, source_file_options: { regular: "-density 96 -depth 8 -quality 85" }, convert_options: { regular: "-posterize 3"} ``` -------------------------------- ### File Migration Script Source: https://github.com/thoughtbot/paperclip/blob/main/MIGRATING-ES.md This Ruby script demonstrates how to migrate files from Paperclip's directory structure to ActiveStorage's expected structure. It iterates through ActiveStorage attachments, copies the source file to the destination directory, and creates necessary subdirectories. ```ruby #!/bin/rails runner class ActiveStorageBlob < ActiveRecord::Base end class ActiveStorageAttachment < ActiveRecord::Base belongs_to :blob, class_name: 'ActiveStorageBlob' belongs_to :record, polymorphic: true end ActiveStorageAttachment.find_each do |attachment| name = attachment.name source = attachment.record.send(name).path dest_dir = File.join( "storage", attachment.blob.key.first(2), attachment.blob.key.first(4).last(2)) dest = File.join(dest_dir, attachment.blob.key) FileUtils.mkdir_p(dest_dir) puts "Moving #{source} to #{dest}" FileUtils.cp(source, dest) end ``` -------------------------------- ### Remove Paperclip Gem and Bundle Update Source: https://github.com/thoughtbot/paperclip/blob/main/MIGRATING.md This demonstrates the Ruby and Bash commands required to remove the Paperclip gem from a project's Gemfile and then update the project's dependencies using Bundler. ```ruby # Remove the 'gem "paperclip"' line from your Gemfile ``` ```bash bundle ``` -------------------------------- ### Paperclip User Table Schema Source: https://github.com/thoughtbot/paperclip/blob/main/MIGRATING-ES.md Illustrates the database table structure generated by Paperclip for storing attachment metadata, including file name, content type, file size, and update timestamp. ```ruby create_table "users", force: :cascade do |t| t.string "avatar_file_name" t.string "avatar_content_type" t.integer "avatar_file_size" t.datetime "avatar_updated_at" end ``` -------------------------------- ### Registering IO Adapters Source: https://github.com/thoughtbot/paperclip/blob/main/README.md Paperclip supports various input forms for files, including UploadedFile, StringIO, Tempfile, and URLs. To handle non-local sources like Data URIs, you need to explicitly register the corresponding IO adapter. It's recommended to only enable adapters you require to avoid potential security risks. ```ruby Paperclip::DataUriAdapter.register ``` -------------------------------- ### Capistrano Deployment Configuration for Paperclip Source: https://github.com/thoughtbot/paperclip/blob/main/README.md Configures Capistrano to manage the `public/system` directory, ensuring that attachments created by Paperclip persist across new deployments. This is achieved by adding `public/system` to the `linked_dirs` array. ```bash set :linked_dirs, fetch(:linked_dirs, []).push('public/system') ``` -------------------------------- ### Controller Eager Loading for Attachments Source: https://github.com/thoughtbot/paperclip/blob/main/MIGRATING.md Illustrates how to prevent N+1 query problems in controllers when displaying attachments. Active Storage provides `.with_attached_attachment_name` scopes, and for nested relationships, `includes` should be used with the attachment and blob names. ```ruby def index @users = User.all.order(:name) end ``` ```ruby