Every repository with this icon (
Every repository with this icon (
Interpolations
Overview
Paperclip’s storage and retrieval of attachments is very flexible. Files can be placed anywhere in the filesystem and can be referenced using any url (assuming that your application knows what to do with that url). Because of the fact that attachments are defined at the class level, instance variables and methods will not be available with the standard “#{var}”-style Ruby variable interpolation. Paperclip gets around this through the use of its own system of interpolations. The standard form looks much like a Ruby symbol. For example:
has_attached_file :avatar, :path => " :rails_root/:attachment/:id/:style.:extension"
Each of those words beginning with : will be replaced with a value when the path is requested. The value is determined by running a bit of code.
Standard Interpolations
The basic interpolations that Paperclip comes with are as follows:
- :rails_root, returns
RAILS_ROOT - :rails_env, returns
RAILS_ENV - :class, returns the name of the class, underscored and pluralized
- The
CassetteTapeclass becomes “cassette_tapes”
- The
- :attachment, returns the name of the attachment as given to
has_attached_file, likewise pluralized- :resume becomes “resumes”
- :basename, returns the basename of the original filename as it was uploaded.
- lolcat.jpg becomes “lolcat”
- :extension, returns the extension of the original filename as it was uploaded.
- startup.wav becomes “wav”
- :id, returns the id of the object. Note that this only works if the object has been saved.
- :id_partition, returns the id of the object in 9 digits split into 3 subdirectories. This is useful if you have a lot of attachments and are running into filesystem limits.
- An id of 12345 becomes “000/012/345”
- :style, returns the style being requested
object.path(:large)would return “../large.png” given the example in the previous section.
Defining Interpolations
Because not everyone’s requirements are the same, it is possible to define your own interpolations. You can do this with the Paperclip.interpolates method.
Paperclip.interpolates :username do |attachment, style|
attachment.instance.username
end
Place this code in config/initializers/paperclip.rb and it will be available to all classes. Once you’ve done this, if you create an attachment like so:
class User < ActiveRecord::Base
has_attached_file :avatar, :path => " :rails_root/public/images/:username.:extension"
end
Then when you call user.avatar.path you will get "./public/images/jyurek.png".






