Dynamic model based styles for Paperclip

One might want to set up dynamic attachment dimensions (or other styles) when generating images with thoughtbot’s paperclip. Styles in paperclip are basically represented in the :styles hash of has_attached_file:

class File
  has_attached_file(
    :attachment,
    :styles => { :thumb => "100x100" }
  )
end

Building a related size model in rails might look the following:

class File < ActiveRecord::Base
  has_many :sizes, :class_name => "FileSize", :dependent => :destroy
 
  has_attached_file(
    :attachment,
    :styles => # styles through FileSize model
  )
 
  def styles
   self.sizes.inject({ :thumb => "100x100" }) do |sizes, size|
      sizes[:"#{size.id}"] = "#{size.width}x#{size.height}"; sizes
    end
  end
end
 
class FileSize < ActiveRecord::Base
  belongs_to :file
end

Using a Proc we can fetch sizes from our FileSize model:

  has_attached_file(
    :attachment,
    :styles => Proc.new { |clip| clip.instance.styles }
  )

Clip is the Paperclip instance which holds an instance-method to get back to the calling Class.

As a last issue one might want to reprocess / regenerated images after creating or destroying sizes:

class FileSize < ActiveRecord::Base
  belongs_to :file
 
  after_create  :reprocess
  after_destroy :reprocess
 
  private
 
  def reprocess
    self.file.attachment.reprocess!
  end
end
Leave a Reply
  1. (required)
  2. (will not be published) (required)