### Basic Model Setup with Paperclip Source: https://github.com/kreeti/kt-paperclip/blob/master/_autodocs/README.md Set up a model to handle file attachments using `has_attached_file`. This example configures styles for an avatar and validates its content type. ```ruby class User < ApplicationRecord has_attached_file :avatar, styles: { medium: "300x300>", thumb: "100x100>" } validates_attachment_content_type :avatar, content_type: /\Aimage/ end ``` -------------------------------- ### Basic Paperclip Attachment Setup with Validations Source: https://github.com/kreeti/kt-paperclip/blob/master/README.md Set up a Paperclip attachment with essential security validations for content type and file name. This example also shows how to explicitly disable file type validation. ```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 ``` -------------------------------- ### Hash Interpolation Example Source: https://github.com/kreeti/kt-paperclip/blob/master/_autodocs/interpolations-urls.md Demonstrates a complete hash interpolation setup and shows the resulting URL. The hash is deterministic based on several factors, including class, ID, and update time. ```ruby has_attached_file :avatar, url: "/system/:hash.:extension", hash_secret: "my-secret-key", hash_data: ":class/:attachment/:id/:updated_at" user = User.find(123) user.avatar.url # => /system/a1b2c3d4e5f6g7h8i9j0k1l2m3n4o5p6.jpg ``` -------------------------------- ### Custom Partitioning Path Interpolation Example Source: https://github.com/kreeti/kt-paperclip/blob/master/_autodocs/storage-api.md Shows how to implement custom directory partitioning for attachment paths. This example uses a simpler structure with class, ID, attachment, style, and filename. ```ruby has_attached_file :avatar, path: ":rails_root/public/:class/:id/:attachment/:style/:filename" # => /var/www/myapp/public/user/1/avatar/thumb/me.jpg ``` -------------------------------- ### Install Dependencies and Run Tests Source: https://github.com/kreeti/kt-paperclip/blob/master/CONTRIBUTING.md Installs all necessary gems for testing across multiple Rails versions and then runs the full test suite. ```bash bundle install bundle exec appraisal install ``` ```bash bundle exec appraisal rake ``` -------------------------------- ### Save New Attachment Example Source: https://github.com/kreeti/kt-paperclip/blob/master/_autodocs/attachment-api.md This example shows how to assign a new file and then use `#save` to write it to storage and delete the old file. ```ruby user.avatar = File.open("new_photo.jpg") user.avatar.save # Write new files, delete old ones ``` -------------------------------- ### Bundler Setup and Version Check Source: https://github.com/kreeti/kt-paperclip/blob/master/features/support/fixtures/preinitializer.txt This code block ensures that Bundler is installed and checks if its version is compatible with older Rails versions. It also sets up the Gemfile path and loads bundled gems, raising errors if Bundler is not found or if gems are missing. ```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 ``` -------------------------------- ### Paperclip Processor #convert Method Example Source: https://github.com/kreeti/kt-paperclip/blob/master/_autodocs/processors-geometry.md An example demonstrating how to use the #convert method within a custom processor to generate a thumbnail with specific quality and strip metadata. ```ruby class Processor < Paperclip::Processor def make output = Tempfile.new(['output', '.jpg']) convert( "-quality 85 -strip :source :dest", source: File.expand_path(@file.path), dest: File.expand_path(output.path) ) output end end ``` -------------------------------- ### Attachment Exists Check Examples Source: https://github.com/kreeti/kt-paperclip/blob/master/_autodocs/attachment-api.md These examples show how to use `#exists?` to check for the presence of the default style or a specific style on storage. ```ruby user.avatar.exists? # => true (checks filesystem) user.avatar.exists?(:thumb) # => true ``` -------------------------------- ### Flat Structure Path Interpolation Example Source: https://github.com/kreeti/kt-paperclip/blob/master/_autodocs/storage-api.md Demonstrates a flat file structure for attachments using custom path interpolation. This example places attachments directly in a specified directory with the ID and filename. ```ruby has_attached_file :avatar, path: ":rails_root/public/attachments/:id_:filename" # => /var/www/myapp/public/attachments/1_me.jpg ``` -------------------------------- ### Paperclip Processor #identify Method Example Source: https://github.com/kreeti/kt-paperclip/blob/master/_autodocs/processors-geometry.md An example showing how to use the #identify method to get the image dimensions (width and height) of the processed file. ```ruby geometry = identify("-format %wx%h :source", source: @file.path) # Returns something like "800x600" ``` -------------------------------- ### Install aws-sdk-s3 Gem Source: https://github.com/kreeti/kt-paperclip/blob/master/_autodocs/storage-api.md Install the necessary gem for S3 integration. ```ruby gem 'aws-sdk-s3' ``` -------------------------------- ### Example: Define and Register Custom Adapter Source: https://github.com/kreeti/kt-paperclip/blob/master/_autodocs/io-adapters.md Shows how to define a custom IO adapter inheriting from AbstractAdapter and then register it. ```ruby module Paperclip class MyStorageAdapter < AbstractAdapter def self.matches?(instance) instance.is_a?(MyStorage) end def read # Implementation end end end Paperclip.io_adapters.register(Paperclip::MyStorageAdapter) ``` -------------------------------- ### Dynamic S3 Credentials Method Example Source: https://github.com/kreeti/kt-paperclip/blob/master/_autodocs/storage-api.md Example of a dynamic method to retrieve S3 credentials within an ActiveRecord model. ```ruby class User < ActiveRecord::Base def s3_credentials { access_key_id: access_key, secret_access_key: secret_key, bucket: team.s3_bucket } end end ``` -------------------------------- ### Install ImageMagick Source: https://github.com/kreeti/kt-paperclip/blob/master/_autodocs/README.md Install ImageMagick, a dependency for image processing, using your system's package manager. ```bash # macOS brew install imagemagick # Ubuntu/Debian sudo apt-get install imagemagick # CentOS/RHEL sudo yum install ImageMagick ``` -------------------------------- ### Example Custom S3ObjectAdapter Source: https://github.com/kreeti/kt-paperclip/blob/master/_autodocs/io-adapters.md An example custom adapter for handling Aws::S3::Object instances. It implements `read`, `original_filename`, `content_type`, `size`, and `path`. ```ruby module Paperclip class S3ObjectAdapter < AbstractAdapter def self.matches?(instance) instance.is_a?(Aws::S3::Object) end def initialize(target, options = {}) super @target = target end def read @target.get.body.read end def original_filename File.basename(@target.key) end def content_type @target.metadata['content-type'] || 'application/octet-stream' end def size @target.size end def path @target.key end end end # Register Paperclip.io_adapters.register(Paperclip::S3ObjectAdapter) # Use s3_object = Aws::S3::Object.new('bucket', 'uploads/image.jpg') user.avatar = s3_object ``` -------------------------------- ### Example: Find Adapter for File and URL Source: https://github.com/kreeti/kt-paperclip/blob/master/_autodocs/io-adapters.md Demonstrates finding adapters for a local file and a remote URL, specifying a hash digest. ```ruby adapter = Paperclip.io_adapters.for( File.open("image.jpg"), hash_digest: Digest::SHA256 ) adapter = Paperclip.io_adapters.for( "http://example.com/image.jpg", hash_digest: Digest::SHA256 ) ``` -------------------------------- ### Example: Crop Geometry Source: https://github.com/kreeti/kt-paperclip/blob/master/_autodocs/processors-geometry.md Demonstrates how to create a thumbnailer with a crop geometry and check if the crop? method returns true. ```ruby # Geometry "100x100#" means crop to square thumbnail = Thumbnail.new(file, geometry: "100x100#") thumbnail.crop? # => true ``` -------------------------------- ### Destroy Attachment Example Source: https://github.com/kreeti/kt-paperclip/blob/master/_autodocs/attachment-api.md This example demonstrates how to use `#destroy` to clear an attachment and save the changes in one step. ```ruby user.avatar.destroy # Clear and save immediately ``` -------------------------------- ### Attachment Dirty Status Example Source: https://github.com/kreeti/kt-paperclip/blob/master/_autodocs/attachment-api.md This example shows how `#dirty?` changes from true after an assignment to false after a successful save. ```ruby user.avatar = File.open("photo.jpg") user.avatar.dirty? # => true user.save user.avatar.dirty? # => false ``` -------------------------------- ### File Attachment Example Source: https://github.com/kreeti/kt-paperclip/blob/master/_autodocs/io-adapters.md Assigning a file to an attachment, which is handled by the FileAdapter. ```ruby user.avatar = File.open("photo.jpg") # => FileAdapter ``` -------------------------------- ### Example: User-Based Paths with Custom Interpolation Source: https://github.com/kreeti/kt-paperclip/blob/master/_autodocs/interpolations-urls.md This example demonstrates creating a custom interpolation `user_slug` to include the user's slug in the file path. It requires registering the interpolation and then using it in the model's `has_attached_file` configuration. ```ruby # config/initializers/paperclip.rb module Paperclip module Interpolations def user_slug(attachment, style) attachment.instance.user.slug end end end Paperclip::Interpolations.register(:user_slug, Paperclip::Interpolations.method(:user_slug)) # In model: class Photo < ApplicationRecord has_attached_file :image, url: "/:user_slug/photos/:id/:filename" end photo = Photo.create(user: user) photo.image.url # => /john-smith/photos/123/landscape.jpg ``` -------------------------------- ### Attachment Staged Status Example Source: https://github.com/kreeti/kt-paperclip/blob/master/_autodocs/attachment-api.md This example illustrates how `#staged?` is true after assigning a file and false after the file has been saved. ```ruby user.avatar = File.open("photo.jpg") user.avatar.staged? # => true user.save user.avatar.staged? # => false ``` -------------------------------- ### Attachment Errors Example Source: https://github.com/kreeti/kt-paperclip/blob/master/_autodocs/attachment-api.md This example demonstrates the output format of the `#errors` method, showing a validation error for a missing file name. ```ruby user.avatar.errors # => {:file_name => ["can't be blank"]} ``` -------------------------------- ### Example: Non-Crop Geometry Source: https://github.com/kreeti/kt-paperclip/blob/master/_autodocs/processors-geometry.md Demonstrates how to create a thumbnailer with a non-crop geometry and check if the crop? method returns false. ```ruby # Geometry "100x100>" means fit within, no crop thumbnail = Thumbnail.new(file, geometry: "100x100>") thumbnail.crop? # => false ``` -------------------------------- ### Attachment File Assignment Check Example Source: https://github.com/kreeti/kt-paperclip/blob/master/_autodocs/attachment-api.md This example demonstrates how `#file?` returns true when the `file_name` attribute is populated, indicating a file is assigned. ```ruby user.avatar.file? # => true (file_name column is not blank) user.avatar.present? # => true (alias) ``` -------------------------------- ### Install Fog Gem Source: https://github.com/kreeti/kt-paperclip/blob/master/_autodocs/storage-api.md Include the 'fog' gem in your Gemfile to enable cloud storage using the Fog library. ```ruby gem 'fog' ``` -------------------------------- ### S3 Credentials YAML File Format Source: https://github.com/kreeti/kt-paperclip/blob/master/_autodocs/storage-api.md Example format for the S3 credentials YAML file. ```yaml # config/s3.yml development: access_key_id: "DEVELOPMENT_KEY" secret_access_key: "DEVELOPMENT_SECRET" bucket: "my-app-development" production: access_key_id: "PRODUCTION_KEY" secret_access_key: "PRODUCTION_SECRET" bucket: "my-app-production" ``` -------------------------------- ### HTTP URL Attachment Example Source: https://github.com/kreeti/kt-paperclip/blob/master/_autodocs/io-adapters.md Assigning an HTTP URL to an attachment, which uses the HttpUrlProxyAdapter after registration. ```ruby user.avatar = "http://example.com/image.jpg" # => HttpUrlProxyAdapter ``` -------------------------------- ### Attachment Attributes Example Source: https://github.com/kreeti/kt-paperclip/blob/master/_autodocs/attachment-api.md This example shows the structure of the Hash returned by `#attributes`, including common keys like `:file_name`, `:file_size`, and `:content_type`. ```ruby user.avatar.attributes # => { # :file_name => "me.jpg", # :file_size => 51234, # :content_type => "image/jpeg", # :updated_at => 2025-02-15 10:30:00, # :fingerprint => "abc123..." # } ``` -------------------------------- ### Product Image Attachment Configuration Source: https://github.com/kreeti/kt-paperclip/blob/master/_autodocs/README.md Example configuration for a Product model's image attachment, including styles, a default URL, and validations for content type and size. ```ruby class Product < ApplicationRecord has_attached_file :image, styles: { thumb: "100x100#", medium: "300x300>", large: "800x800>" }, default_url: "/images/missing.png" validates_attachment_content_type :image, content_type: /\Aimage/ validates_attachment_size :image, less_than: 10.megabytes end ``` -------------------------------- ### Model-Level Storage Backend Configuration Source: https://github.com/kreeti/kt-paperclip/blob/master/_autodocs/storage-api.md Set the storage backend on a per-model basis, allowing different models to use different storage solutions. This example uses S3 for production and filesystem for others. ```ruby class User < ActiveRecord::Base storage = Rails.env.production? ? :s3 : :filesystem has_attached_file :avatar, storage: storage, s3_credentials: storage == :s3 ? {...} : {} end ``` -------------------------------- ### Paperclip Geometry Styles Configuration Examples Source: https://github.com/kreeti/kt-paperclip/blob/master/_autodocs/processors-geometry.md Illustrates various geometry string formats and modifiers for configuring attached file styles in Paperclip. ```ruby has_attached_file :avatar, styles: { # Fit within 300x300, preserve aspect ratio, no cropping medium: "300x300>", # Create 100x100 square thumbnail, crop excess thumb: "100x100#", # Exact dimensions, no aspect ratio preservation square: "150x150!", # Resize only if larger display: "800x600>", # Resize to percentage preview: "50%" } ``` -------------------------------- ### Copy Attachment Example Source: https://github.com/kreeti/kt-paperclip/blob/master/_autodocs/io-adapters.md Copying an existing attachment from another object, which uses the AttachmentAdapter. ```ruby user.avatar = other_user.avatar # => AttachmentAdapter ``` -------------------------------- ### StringIO Attachment Example Source: https://github.com/kreeti/kt-paperclip/blob/master/_autodocs/io-adapters.md Assigning data from a StringIO object to an attachment, handled by the StringIOAdapter. ```ruby user.avatar = StringIO.new(data) # => StringIOAdapter ``` -------------------------------- ### Tempfile Attachment Example Source: https://github.com/kreeti/kt-paperclip/blob/master/_autodocs/io-adapters.md Assigning a Tempfile object to an attachment, also handled by the FileAdapter. ```ruby temp = Tempfile.new("upload") user.avatar = temp # => FileAdapter ``` -------------------------------- ### Validation Error Example Source: https://github.com/kreeti/kt-paperclip/blob/master/_autodocs/validators-api.md Demonstrates how validation errors are stored in the model's error hash. This example shows a file size validation error. ```ruby user = User.new user.avatar = File.open("too_large.jpg") # 10MB file user.validate user.errors[:avatar] # => ["file size must be less than 5 MB"] ``` -------------------------------- ### Creating Custom Processors Source: https://github.com/kreeti/kt-paperclip/blob/master/_autodocs/processors-geometry.md Guidelines and an example for creating custom Paperclip processors. Custom processors must inherit from `Paperclip::Processor` and implement the `#make` method. ```APIDOC ## Creating Custom Processors ### Requirements: 1. Inherit from `Paperclip::Processor` 2. Implement `#make` method 3. Be defined in the `Paperclip` module namespace 4. Be placed in `lib/paperclip/` or `lib/paperclip_processors/` ### Example: Custom Watermark Processor ```ruby module Paperclip class WatermarkProcessor < Processor def make @attachment.post_processing = true watermark_path = options[:watermark_path] || '/assets/watermark.png' output = TempfileFactory.new.generate begin convert( "-composite -gravity southeast -geometry +10+10 " \ ":watermark :source :dest", watermark: watermark_path, source: File.expand_path(@file.path), dest: File.expand_path(output.path) ) rescue Terrapin::ExitStatusError => e raise Paperclip::Error.new("Watermarking failed: #{e.message}") end output end end end ``` ### Usage: ```ruby class Product < ActiveRecord::Base has_attached_file :image, processors: [:thumbnail, :watermark], styles: { original: { geometry: '800x800>', watermark_path: '/assets/watermark.png' }, thumb: '100x100#' } end ``` ``` -------------------------------- ### Data URI Attachment Example Source: https://github.com/kreeti/kt-paperclip/blob/master/_autodocs/io-adapters.md Assigning a Data URI to an attachment, which uses the DataUriAdapter after registration. ```ruby user.avatar = "data:image/jpeg;base64,..." # => DataUriAdapter ``` -------------------------------- ### Get IO Adapter Registry Source: https://github.com/kreeti/kt-paperclip/blob/master/_autodocs/io-adapters.md Access the IO adapter registry to manage and find adapters. ```ruby Paperclip.io_adapters ``` -------------------------------- ### Global Paperclip Configuration Options Source: https://github.com/kreeti/kt-paperclip/blob/master/_autodocs/README.md Set global Paperclip options in an initializer file. This example disables logging, suppresses errors on processing failure, specifies the ImageMagick path, and enables EXIF orientation. ```ruby Paperclip.options[:log] = false Paperclip.options[:whiny] = false # Disable errors on processing failure Paperclip.options[:imagemagick_path] = "/usr/local/bin/" Paperclip.options[:use_exif_orientation] = true ``` -------------------------------- ### FactoryBot Example for User Avatar Source: https://github.com/kreeti/kt-paperclip/blob/master/README.md Defines a FactoryBot factory for a User model, including an avatar attachment. This is used for setting up test data. ```ruby FactoryBot.define do factory :user do avatar { File.new("#{Rails.root}/spec/support/fixtures/image.jpg") } end end ``` -------------------------------- ### Factory Bot Setup for User Avatar Source: https://github.com/kreeti/kt-paperclip/blob/master/_autodocs/README.md Define a Factory Bot factory for the User model, assigning a fixture file to the avatar attribute for testing purposes. ```ruby FactoryBot.define do factory :user do avatar { File.new("#{Rails.root}/spec/fixtures/avatar.jpg") } end end ``` -------------------------------- ### Defining Multiple Image Styles Source: https://github.com/kreeti/kt-paperclip/blob/master/_autodocs/README.md Configure different image transformations (styles) for an attachment. This example defines styles for medium, thumbnail, and PNG formats. ```ruby has_attached_file :avatar, styles: { # Fit within 300x300, preserve aspect ratio medium: "300x300>", # Create 100x100 square, crop excess thumb: "100x100#", # Specific format png: ["300x300>", :png] } ``` -------------------------------- ### Customizing URL and Path with Interpolations Source: https://github.com/kreeti/kt-paperclip/blob/master/_autodocs/README.md Customize the URL and file path patterns using interpolations. This example shows a common pattern for organizing attachments by class, attachment name, and record ID. ```ruby has_attached_file :avatar, url: "/system/:class/:attachment/:id/:style/:filename", path: ":rails_root/public:url" ``` -------------------------------- ### Dynamic Configuration with Procs Source: https://github.com/kreeti/kt-paperclip/blob/master/_autodocs/configuration-errors.md Demonstrates how to use Procs for dynamic configuration of attachment options like path, styles, and processors, evaluated at assignment time. ```ruby has_attached_file :document, path: Proc.new { |attachment| "/uploads/#{attachment.instance.user_id}/:attachment/:id/:filename" }, styles: Proc.new { |attachment| attachment.instance.video? ? { thumb: "100x100#" } : {} }, processors: Proc.new { |instance| instance.apply_filters? ? [:thumbnail, :watermark] : [:thumbnail] } ``` -------------------------------- ### Custom Object Attachment Example Source: https://github.com/kreeti/kt-paperclip/blob/master/_autodocs/io-adapters.md Assigning a custom object with #read and #rewind methods, which defaults to the IdentityAdapter. ```ruby user.avatar = MyCustomObject.new # => IdentityAdapter (if it has #read and #rewind) ``` -------------------------------- ### Conditional Validation Examples Source: https://github.com/kreeti/kt-paperclip/blob/master/_autodocs/validators-api.md Demonstrates how to use `:if` and `:unless` options for conditional validation of attachments. The `:if` option uses a method, while `:unless` uses a lambda. ```ruby class Post < ActiveRecord::Base has_attached_file :image # Only validate image if user is uploading one validates_attachment_content_type :image, content_type: /\Aimage/, if: :image_provided? # Using a lambda validates_attachment_size :image, less_than: 5.megabytes, unless: lambda { |post| post.premium_user? } def image_provided? image_file_name.present? end end ``` -------------------------------- ### Registering Custom Adapters Source: https://github.com/kreeti/kt-paperclip/blob/master/_autodocs/io-adapters.md Demonstrates the correct order for registering custom adapters, ensuring specific adapters are checked before generic ones. ```ruby # config/initializers/paperclip.rb # Register custom adapters before generic ones Paperclip.io_adapters.register(MySpecificAdapter) Paperclip.io_adapters.register(MyGenericAdapter) # Optional adapters must be registered explicitly Paperclip::DataUriAdapter.register Paperclip::HttpUrlProxyAdapter.register ``` -------------------------------- ### Document Storage with Date Organization Source: https://github.com/kreeti/kt-paperclip/blob/master/_autodocs/interpolations-urls.md Organizes documents by their update date in the file path. This example shows how to use `:updated_at` for directory structuring. ```ruby class Document < ApplicationRecord has_attached_file :pdf, path: ":rails_root/documents/:updated_at/:id/:filename", url: "/documents/:updated_at/:id/:filename" end document = Document.create(pdf: File.open("report.pdf")) document.pdf.path # => /var/www/app/documents/2025-02-15/789/report.pdf document.pdf.url # => /documents/2025-02-15/789/report.pdf ``` -------------------------------- ### Model Setup with Paperclip Source: https://github.com/kreeti/kt-paperclip/blob/master/_autodocs/QUICK_REFERENCE.md Declare an attachment in your model using `has_attached_file` and add validations for content type and size. This sets up the basic structure for handling file uploads. ```ruby class User < ApplicationRecord # Declare attachment has_attached_file :avatar, styles: { medium: "300x300>", thumb: "100x100>" }, storage: :filesystem # Add validation validates_attachment_content_type :avatar, content_type: /\Aimage/ validates_attachment_size :avatar, less_than: 5.megabytes end ``` -------------------------------- ### Building and Publishing the Gem Source: https://github.com/kreeti/kt-paperclip/blob/master/RELEASING.md Commands to build the gem locally and then push it to the gem repository. Replace VERSION with the actual version number. ```bash gem build paperclip.gemspec ``` ```bash gem push paperclip-VERSION.gem ``` -------------------------------- ### Default Path Interpolation Example Source: https://github.com/kreeti/kt-paperclip/blob/master/_autodocs/storage-api.md Illustrates the default path structure for storing attachments, which includes the Rails root, public directory, class name, attachment name, ID, style, and filename. ```ruby has_attached_file :avatar # => /var/www/myapp/public/system/users/avatars/000/000/001/original/me.jpg ``` -------------------------------- ### Paperclip Attachment Configuration with Custom Processor Source: https://github.com/kreeti/kt-paperclip/blob/master/_autodocs/processors-geometry.md Example of configuring an ActiveRecord model to use custom processors, including the :watermark processor, and defining styles with specific options like watermark_path. ```ruby class Product < ActiveRecord::Base has_attached_file :image, processors: [:thumbnail, :watermark], styles: { original: { geometry: '800x800>', watermark_path: '/assets/watermark.png' }, thumb: '100x100#' } end ``` -------------------------------- ### Paperclip.io_adapters.for Source: https://github.com/kreeti/kt-paperclip/blob/master/_autodocs/io-adapters.md Finds and instantiates an appropriate adapter for the given input. It iterates through registered adapters, testing each with the `matches?` method, and instantiates the first one that matches. An error is raised if no adapter is found. ```APIDOC ## Paperclip.io_adapters.for(input, options = {}) ### Description Finds and instantiates an appropriate adapter for the input. It tests the input against each registered adapter's `matches?` method and instantiates the first matching adapter. Raises an error if no adapter matches. ### Method `Paperclip.io_adapters.for` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters - **input** (Various) - Required - File object, string, or other IO source - **options** (Hash) - Optional - Options passed to adapter (e.g., `:hash_digest`) ### Request Example ```ruby adapter = Paperclip.io_adapters.for( File.open("image.jpg"), hash_digest: Digest::SHA256 ) adapter = Paperclip.io_adapters.for( "http://example.com/image.jpg", hash_digest: Digest::SHA256 ) ``` ### Response #### Success Response (200) - **Adapter instance** (subclass of AbstractAdapter) - The instantiated adapter object. #### Response Example ```json { "adapter_type": "FileAdapter", "filename": "image.jpg", "content_type": "image/jpeg" } ``` ### Error Handling - Raises an error if no adapter matches the input. ``` -------------------------------- ### Handling Validation Errors for File Size Source: https://github.com/kreeti/kt-paperclip/blob/master/_autodocs/README.md Demonstrates how to trigger and inspect validation errors for an avatar attachment. This example assigns a file exceeding the size limit and checks the errors. ```ruby user = User.new user.avatar = File.open("large_file.jpg") # 50MB, limit is 10MB user.validate user.errors[:avatar] # => ["file size must be less than 10 MB"] ``` -------------------------------- ### #make Source: https://github.com/kreeti/kt-paperclip/blob/master/_autodocs/processors-geometry.md Creates the thumbnail and returns a Tempfile. This method handles the core image processing logic, including geometry detection, transformation calculation, and option application. ```APIDOC ## #make ### Description Creates the thumbnail and returns a Tempfile. ### Method Signature ```ruby def make ``` ### Returns - **Type:** Tempfile - **Description:** processed image file ### Behavior - Detects source image geometry using ImageMagick identify - Calculates transformation (scale/crop) based on target geometry - Executes convert command with source/convert options - Handles animation for GIF files - Auto-rotates based on EXIF orientation if enabled ### Example ```ruby class Product < ActiveRecord::Base has_attached_file :image, styles: { thumb: { geometry: '100x100#', convert_options: '-quality 75 -strip' } } end product = Product.create(image: File.open('photo.jpg')) # Thumbnail processor automatically creates 100x100 cropped thumbnail ``` ``` -------------------------------- ### Handling 'No Adapter Found' Error Source: https://github.com/kreeti/kt-paperclip/blob/master/_autodocs/io-adapters.md Illustrates the error raised when no suitable adapter is found for an object and suggests solutions. ```ruby user.avatar = some_object # => Paperclip::Errors::AdapterNotFound ``` -------------------------------- ### Product Images with CDN Interpolation Source: https://github.com/kreeti/kt-paperclip/blob/master/_autodocs/interpolations-urls.md Configures product image storage and retrieval using a CDN URL. Demonstrates how to specify a custom domain for URLs. ```ruby class Product < ApplicationRecord has_attached_file :image, url: "https://cdn.example.com/products/:id/:style/:filename", path: ":rails_root/public/products/:id/:style/:filename", styles: { thumb: "100x100#", display: "400x400>" } end product = Product.find(456) product.image.url # => https://cdn.example.com/products/456/original/widget.jpg product.image.url(:thumb) # => https://cdn.example.com/products/456/thumb/widget.jpg ``` -------------------------------- ### Dynamic Avatar Styles Based on User Premium Status Source: https://github.com/kreeti/kt-paperclip/blob/master/_autodocs/README.md Implement dynamic image styles for avatar attachments based on an instance's 'premium?' status. Premium users get larger styles, while others only get a thumbnail. ```ruby class User < ApplicationRecord has_attached_file :avatar, styles: lambda { |attachment| attachment.instance.premium? ? { thumb: "100x100#", medium: "300x300>", large: "800x800>" } : { thumb: "100x100#" } } end ``` -------------------------------- ### Get Attachment Size Source: https://github.com/kreeti/kt-paperclip/blob/master/_autodocs/attachment-api.md Returns the file size of the attachment in bytes. ```ruby attachment.size ``` ```ruby user.avatar.size # => 51234 ``` -------------------------------- ### Find IO Adapter for Input Source: https://github.com/kreeti/kt-paperclip/blob/master/_autodocs/io-adapters.md Instantiates an appropriate adapter for a given input source. Options can be passed to the adapter. ```ruby adapter = Paperclip.io_adapters.for(input, adapter_options) ``` -------------------------------- ### Get Smaller Dimension Source: https://github.com/kreeti/kt-paperclip/blob/master/_autodocs/processors-geometry.md Returns the smaller of the two dimensions (width or height). ```ruby geometry.smaller ``` -------------------------------- ### Get Larger Dimension Source: https://github.com/kreeti/kt-paperclip/blob/master/_autodocs/processors-geometry.md Returns the larger of the two dimensions (width or height). ```ruby geometry.larger ``` -------------------------------- ### Get Attachment Content Type Source: https://github.com/kreeti/kt-paperclip/blob/master/_autodocs/attachment-api.md Returns the MIME type of the attachment, such as 'image/jpeg'. ```ruby attachment.content_type ``` ```ruby user.avatar.content_type # => "image/jpeg" ``` -------------------------------- ### Thumbnail Initialization Source: https://github.com/kreeti/kt-paperclip/blob/master/_autodocs/processors-geometry.md Initializes a new thumbnail processor with a file, options, and an optional attachment. It allows for detailed control over thumbnail generation. ```APIDOC ## initialize ### Description Initializes a new thumbnail processor with a file, options, and an optional attachment. ### Method Signature ```ruby def initialize(file, options = {}, attachment = nil) ``` ### Parameters #### `file` - **Type:** File - **Description:** Image file to thumbnail #### `options` - **Type:** Hash - **Description:** Thumbnail options ### Options #### `:geometry` - **Type:** String - **Required:** Yes - **Description:** Resize geometry (e.g., "100x100=", "300x300#") #### `:source_file_options` - **Type:** String/Array - **Required:** No - **Description:** Flags for reading source file #### `:convert_options` - **Type:** String/Array - **Required:** No - **Description:** Flags for image conversion #### `:whiny` - **Type:** Boolean - **Required:** No - **Description:** Raise errors on failure (default: true) #### `:format` - **Type:** String - **Required:** No - **Description:** Output format (e.g., "jpg", "png") #### `:animated` - **Type:** Boolean - **Required:** No - **Description:** Merge animated layers (default: true) #### `:auto_orient` - **Type:** Boolean - **Required:** No - **Description:** Auto-rotate based on EXIF (default: true) #### `:frame_index` - **Type:** Integer - **Required:** No - **Description:** Frame to extract (for multi-frame formats) #### `:file_geometry_parser` - **Type:** Object - **Required:** No - **Description:** Parser for reading file geometry #### `:string_geometry_parser` - **Type:** Object - **Required:** No - **Description:** Parser for geometry strings ``` -------------------------------- ### Get Geometry Aspect Ratio Source: https://github.com/kreeti/kt-paperclip/blob/master/_autodocs/processors-geometry.md Returns the aspect ratio of the geometry (width / height). ```ruby Geometry.new(800, 600).aspect # => 1.333... (4:3 aspect) Geometry.new(1280, 720).aspect # => 1.777... (16:9 aspect) ``` -------------------------------- ### Get Original Filename Source: https://github.com/kreeti/kt-paperclip/blob/master/_autodocs/attachment-api.md Retrieves the original name of the uploaded file as provided by the user. ```ruby attachment.original_filename ``` ```ruby user.avatar = File.open("my_photo.jpg") user.avatar.original_filename # => "my_photo.jpg" ``` -------------------------------- ### URI Object Attachment Example Source: https://github.com/kreeti/kt-paperclip/blob/master/_autodocs/io-adapters.md Assigning a URI object to an attachment, which uses the UriAdapter if registered. ```ruby user.avatar = URI.parse("http://example.com/image.jpg") # => UriAdapter (if registered) ``` -------------------------------- ### #transformation_to Source: https://github.com/kreeti/kt-paperclip/blob/master/_autodocs/processors-geometry.md Calculates the necessary scale and crop commands to transform the current geometry to a target geometry, with an option to crop. ```APIDOC ## #transformation_to(target_geometry, crop = false) ### Description Calculates the transformation (scale and crop) needed to convert from current geometry to target. ### Parameters #### Path Parameters - **target_geometry** (Geometry) - Required - Target dimensions - **crop** (Boolean) - Optional - Whether to crop or fit ### Returns Array[String, String] - scale command and crop command ### Request Example ```ruby scale_command, crop_command = current.transformation_to(target, true) ``` ``` -------------------------------- ### Configure Source File Options for PDFs Source: https://github.com/kreeti/kt-paperclip/blob/master/_autodocs/processors-geometry.md Use `source_file_options` to specify parameters like density when reading source files, particularly useful for PDFs to control resolution. ```ruby has_attached_file :image, source_file_options: "-density 96 -depth 8" ``` -------------------------------- ### Get Attachment Creation Timestamp Source: https://github.com/kreeti/kt-paperclip/blob/master/_autodocs/attachment-api.md Returns the timestamp indicating when the attachment file was originally assigned. ```ruby attachment.created_at ``` -------------------------------- ### Select Storage Backend Source: https://github.com/kreeti/kt-paperclip/blob/master/_autodocs/storage-api.md Specify a storage backend using the `:storage` option in `has_attached_file`. Supported backends include `:filesystem`, `:s3`, and `:fog`. ```ruby class User < ActiveRecord::Base has_attached_file :avatar, storage: :filesystem # OR has_attached_file :avatar, storage: :s3 # OR has_attached_file :avatar, storage: :fog end ``` -------------------------------- ### Basic Attachment Usage Source: https://github.com/kreeti/kt-paperclip/blob/master/_autodocs/model-integration.md Demonstrates defining an attachment, creating/updating with an attachment, accessing properties, generating URLs, clearing, and checking attachment status. ```ruby class User < ApplicationRecord has_attached_file :avatar, styles: { thumb: "100x100#", medium: "300x300>" } validates_attachment_content_type :avatar, content_type: /\Aimage/ end # Create with attachment user = User.create( email: "john@example.com", avatar: params[:user][:avatar] ) # Update attachment user.avatar = File.open("new_photo.jpg") user.save # Access attachment properties user.avatar.original_filename user.avatar.content_type user.avatar.size user.avatar.created_at # Generate URLs for all styles user.avatar.url(:original) user.avatar.url(:thumb) user.avatar.url(:medium) # Clear attachment user.avatar = nil user.save # File is deleted from storage # Check attachment status user.avatar.file? # => true if assigned user.avatar.exists? # => true if file exists on disk/cloud user.avatar.dirty? # => true if unsaved changes ``` -------------------------------- ### Rails Form Upload Attachment Example Source: https://github.com/kreeti/kt-paperclip/blob/master/_autodocs/io-adapters.md Assigning an attachment from a Rails form upload, which uses the UploadedFileAdapter. ```ruby user.avatar = params[:user][:avatar] # => UploadedFileAdapter ``` -------------------------------- ### Get Attachment Update Timestamp Source: https://github.com/kreeti/kt-paperclip/blob/master/_autodocs/attachment-api.md Returns the timestamp indicating the last time the attachment file was modified. ```ruby attachment.updated_at ``` -------------------------------- ### Custom Storage Adapter Implementation Source: https://github.com/kreeti/kt-paperclip/blob/master/_autodocs/storage-api.md Define a custom storage adapter by extending Paperclip::Storage. This allows integration with any storage system. ```ruby module Paperclip module Storage module MyStorage def self.extended(base); end def exists?(style_name = default_style) # Check if file exists end def flush_writes # Write queued files to storage end def flush_deletes # Delete queued files from storage end def copy_to_local_file(style, local_path) # Copy file from storage to local filesystem end end end end # Use: has_attached_file :avatar, storage: :my_storage ``` -------------------------------- ### Get Attachment Fingerprint Source: https://github.com/kreeti/kt-paperclip/blob/master/_autodocs/attachment-api.md Returns a hash or fingerprint of the file content, typically an MD5 hash by default. ```ruby attachment.fingerprint ``` ```ruby user.avatar.fingerprint # => "abc123def456..." ``` -------------------------------- ### Filesystem Storage Configuration Source: https://github.com/kreeti/kt-paperclip/blob/master/_autodocs/storage-api.md Configures options for the default filesystem storage backend, including path and URL. ```APIDOC ## Module: Paperclip::Storage::Filesystem The default storage backend. Files are saved to the local filesystem and served directly or through Rails. ### Configuration When using filesystem storage, configure the following options: ```ruby has_attached_file :avatar, storage: :filesystem, path: ":rails_root/public/system/:class/:attachment/:id/:style/:filename", url: "/system/:class/:attachment/:id/:filename" ``` **Options:** | Option | Type | Default | Description | |--------|------|---------|-------------| | `:path` | String | ":rails_root/public:url" | Filesystem path where files are stored | | `:url` | String | "/system/:class/:attachment/:id_partition/:style/:filename" | Public URL for served files | | `:override_file_permissions` | Integer/Boolean | `0666 & ~umask` | Unix permissions for saved files (octal) | ``` -------------------------------- ### Use HttpUrlProxyAdapter Source: https://github.com/kreeti/kt-paperclip/blob/master/_autodocs/io-adapters.md Assign an HTTP/HTTPS URL string to an attachment after registering HttpUrlProxyAdapter. Strict validation is required. ```ruby user.avatar = "http://example.com/user/profile.jpg" # After registration ``` -------------------------------- ### Migration Helper to Create Attachment Column Source: https://github.com/kreeti/kt-paperclip/blob/master/_autodocs/configuration-errors.md Example of a Rails migration to create a table with a Paperclip attachment column. ```ruby class CreateUsers < ActiveRecord::Migration[6.0] def change create_table :users do |t| t.string :name t.attachment :avatar t.timestamps end end end ``` -------------------------------- ### Using Custom Processors Source: https://github.com/kreeti/kt-paperclip/blob/master/_autodocs/QUICK_REFERENCE.md Configure an attachment to use custom processors like `:watermark` along with standard ones like `:thumbnail`, specifying custom options like `watermark_path`. ```ruby has_attached_file :image, processors: [:thumbnail, :watermark], styles: { thumb: { geometry: '100x100#', watermark_path: '/assets/watermark.png' } } ``` -------------------------------- ### Get Attachment Filesystem Path Source: https://github.com/kreeti/kt-paperclip/blob/master/_autodocs/attachment-api.md Returns the filesystem path for the attachment file. Useful for direct file access. ```ruby attachment.path(style_name = default_style) ``` ```ruby user.avatar.path # => "/var/app/public/system/users/1/original/me.jpg" user.avatar.path(:thumb) # => "/var/app/public/system/users/1/thumb/me.jpg" ``` -------------------------------- ### Development Configuration: Filesystem Storage Source: https://github.com/kreeti/kt-paperclip/blob/master/_autodocs/README.md Configure Paperclip to use the local filesystem for storage in the development environment. This is often faster for local development than S3. ```ruby # config/environments/development.rb config.paperclip_defaults = { storage: :filesystem } ``` -------------------------------- ### Read Attachment Properties Source: https://github.com/kreeti/kt-paperclip/blob/master/_autodocs/model-integration.md Access properties of an attachment instance to get its filename, size, content type, and URLs. ```ruby user = User.find(1) user.avatar.original_filename # => "photo.jpg" user.avatar.size # => 102400 user.avatar.content_type # => "image/jpeg" user.avatar.url # => "/system/users/1/original/photo.jpg" user.avatar.url(:thumb) # => "/system/users/1/thumb/photo.jpg" ``` -------------------------------- ### Enforce ImageMagick Version Source: https://github.com/kreeti/kt-paperclip/blob/master/_autodocs/configuration-errors.md Force Paperclip to use a specific ImageMagick version (e.g., '7') if multiple versions are installed. ```ruby # Force ImageMagick 7 (if both 6 and 7 are installed) Paperclip.options[:imagemagick_version] = "7" ``` -------------------------------- ### Registering a Custom Interpolation Source: https://github.com/kreeti/kt-paperclip/blob/master/_autodocs/interpolations-urls.md Custom interpolation variables can be registered in an initializer file. This example shows how to register a 'custom' interpolation. ```ruby # config/initializers/paperclip.rb module Paperclip module Interpolations def custom(attachment, style) attachment.instance.custom_value end end end Paperclip::Interpolations.register(:custom, Paperclip::Interpolations.method(:custom)) ``` -------------------------------- ### Registering HTTP URL Adapter Source: https://github.com/kreeti/kt-paperclip/blob/master/_autodocs/io-adapters.md Enables downloading attachments from HTTP URLs. ```ruby Paperclip::HttpUrlProxyAdapter.register ``` -------------------------------- ### Get Attachment Styles Source: https://github.com/kreeti/kt-paperclip/blob/master/_autodocs/attachment-api.md Returns a hash of normalized Style objects for the attachment. It evaluates dynamic styles and caches results. ```ruby attachment.styles ``` ```ruby has_attached_file :avatar, styles: { thumb: "100x100>", medium: "300x300>" } user.avatar.styles # => {:thumb => Style, :medium => Style} # Dynamic styles has_attached_file :avatar, styles: lambda { |att| { thumb: (att.instance.premium? ? "200x200" : "100x100") } } ``` -------------------------------- ### AttachmentFileNameValidator Examples Source: https://github.com/kreeti/kt-paperclip/blob/master/_autodocs/validators-api.md Validates that the original filename matches a pattern. Use `validates_attachment_file_name` for direct validation or `validates_with AttachmentFileNameValidator` for more explicit control. ```ruby class Document < ActiveRecord::Base has_attached_file :pdf validates_attachment_file_name :pdf, matches: /\.pdf\z/ # OR validates :pdf, file_name: { matches: [/\.pdf\z/, /\.txt\z/] } # OR validates_with AttachmentFileNameValidator, attributes: [:pdf], matches: /\.(pdf|doc|docx)\z/ end ``` ```ruby class Pdf < ActiveRecord::Base has_attached_file :document validates_attachment_file_name :document, matches: /\.pdf\z/ end ``` ```ruby class Document < ActiveRecord::Base has_attached_file :file validates_attachment_file_name :file, matches: [/\.pdf\z/, /\.doc\z/, /\.docx\z/] end ``` ```ruby class Config < ActiveRecord::Base has_attached_file :upload validates_attachment_file_name :upload, not: /\.(exe|bat|sh)\z/ end ``` ```ruby class Media < ActiveRecord::Base has_attached_file :file validates_attachment_file_name :file, matches: /\.gif\z/, if: :image_file? def image_file? content_type.start_with?("image") end end ``` -------------------------------- ### Tagging a Release Source: https://github.com/kreeti/kt-paperclip/blob/master/RELEASING.md Use this command to tag a new release with the specified version. Ensure the version number is correct. ```bash git tag -m 'vVERSION' vVERSION ``` -------------------------------- ### Per-Environment Storage Backend Configuration Source: https://github.com/kreeti/kt-paperclip/blob/master/_autodocs/storage-api.md Dynamically set the default storage backend based on the current Rails environment. This allows different storage strategies for development and production. ```ruby # config/initializers/paperclip.rb case Rails.env when 'development' Paperclip::Attachment.default_options[:storage] = :filesystem when 'production' Paperclip::Attachment.default_options[:storage] = :s3 Paperclip::Attachment.default_options[:s3_credentials] = { access_key_id: ENV['AWS_ACCESS_KEY_ID'], secret_access_key: ENV['AWS_SECRET_ACCESS_KEY'], bucket: ENV['S3_BUCKET'] } end ``` -------------------------------- ### Get Attachment Errors Source: https://github.com/kreeti/kt-paperclip/blob/master/_autodocs/attachment-api.md The `#errors` method returns a Hash containing any validation errors associated with the attachment, keyed by the field name. ```ruby attachment.errors ``` -------------------------------- ### Configure Individual Validation Error Reporting Source: https://github.com/kreeti/kt-paperclip/blob/master/README.md Specify how validation errors are added for a single attachment. This example ensures errors are only reported on the attribute itself. ```ruby validates_attachment :document, content_type: { content_type: "application/pdf" }, add_validation_errors_to: :attribute ``` -------------------------------- ### Adapter Interface - size Method Source: https://github.com/kreeti/kt-paperclip/blob/master/_autodocs/io-adapters.md The `#size` method returns the file size in bytes. It is auto-calculated if not specified. ```ruby adapter.size # => 102400 (bytes) ``` -------------------------------- ### Create Table with Attachments Migration Helper Source: https://github.com/kreeti/kt-paperclip/blob/master/_autodocs/model-integration.md Use `t.attachment` within `create_table` to define attachment columns during table creation. ```ruby class CreateUsers < ActiveRecord::Migration[6.0] def change create_table :users do |t| t.string :email t.attachment :avatar, :resume t.timestamps end end end ``` -------------------------------- ### Short Public URLs with Hash Source: https://github.com/kreeti/kt-paperclip/blob/master/_autodocs/interpolations-urls.md Shows how to create concise public URLs using hash interpolation, particularly useful for assets like documents. ```ruby has_attached_file :document, url: "/d/:hash", hash_secret: "key", hash_data: ":class/:id" # => /d/a1b2c3d4e5f6g7h8.pdf ``` -------------------------------- ### AttachmentSizeValidator Examples Source: https://github.com/kreeti/kt-paperclip/blob/master/_autodocs/validators-api.md Validates that the file size is within acceptable bounds. Use `validates_attachment_size` for direct validation or `validates_with AttachmentSizeValidator` for more explicit control. ```ruby class User < ActiveRecord::Base has_attached_file :avatar validates_attachment_size :avatar, less_than: 5.megabytes # OR validates :avatar, size: { in: 0..10.megabytes } # OR validates_with AttachmentSizeValidator, attributes: [:avatar], less_than: 5.megabytes end ``` ```ruby class User < ActiveRecord::Base has_attached_file :avatar validates_attachment_size :avatar, less_than: 5.megabytes end ``` ```ruby class Document < ActiveRecord::Base has_attached_file :pdf validates_attachment_size :pdf, in: 1.kilobyte..50.megabytes end ``` ```ruby class Video < ActiveRecord::Base has_attached_file :file validates_attachment_size :file, greater_than: 1.megabyte, less_than: 500.megabytes end ``` ```ruby class User < ActiveRecord::Base has_attached_file :storage validates_attachment_size :storage, less_than: lambda { |att| att.instance.max_storage_size } def max_storage_size premium? ? 100.megabytes : 10.megabytes end end ``` -------------------------------- ### Get Attachment Attributes Source: https://github.com/kreeti/kt-paperclip/blob/master/_autodocs/attachment-api.md The `#attributes` method returns a Hash containing all attachment-related database columns, such as file name, size, and content type. ```ruby attachment.attributes ``` -------------------------------- ### Basic S3 Configuration Source: https://github.com/kreeti/kt-paperclip/blob/master/_autodocs/storage-api.md Configure Paperclip to use S3 storage with essential options. ```ruby has_attached_file :avatar, storage: :s3, s3_credentials: { access_key_id: "...", secret_access_key: "...", bucket: "my-bucket" }, s3_region: "us-east-1", url: ":s3_path_url" ``` -------------------------------- ### Get Expiring Attachment URL Source: https://github.com/kreeti/kt-paperclip/blob/master/_autodocs/attachment-api.md Generates a URL that may expire, suitable for cloud storage. For filesystem storage, it behaves like `#url`. ```ruby attachment.expiring_url(_time = 3600, style_name = default_style) ``` ```ruby user.avatar.expiring_url # => "/system/users/1/original/me.jpg" user.avatar.expiring_url(86400) # => 1-day expiring URL for S3 user.avatar.expiring_url(3600, :thumb) ``` -------------------------------- ### Get Attachment URL Source: https://github.com/kreeti/kt-paperclip/blob/master/_autodocs/attachment-api.md Retrieves the public URL for an attachment. Supports specifying a style name and options for cache-busting timestamps or URL escaping. ```ruby attachment.url(style_name = default_style, options = {}) ``` ```ruby user.avatar.url # => "/system/users/avatars/1/original/me.jpg" user.avatar.url(:thumb) # => "/system/users/avatars/1/thumb/me.jpg" user.avatar.url(:medium, timestamp: false) # => URL without timestamp user.avatar.url(:thumb, escape: false) # => unescaped URL ``` -------------------------------- ### Register HttpUrlProxyAdapter Source: https://github.com/kreeti/kt-paperclip/blob/master/_autodocs/io-adapters.md Register the HttpUrlProxyAdapter to handle HTTP/HTTPS URLs as strings. This is optional and requires explicit registration. ```ruby # config/initializers/paperclip.rb Paperclip::HttpUrlProxyAdapter.register ```