Skip to content
This repository has been archived by the owner on Jul 13, 2023. It is now read-only.

Interpolations

Sameer S edited this page Dec 22, 2016 · 9 revisions

Interpolations are the preferred method of allowing urls and paths to be dynamic. They work for :url, :path, and :default_url. See Paperclip::Interpolations for a list of some of the built-in interpolations.

You can add your own interpolations very easily. Say, for example, that you have an article with a category, and you wanted to have a different default image based on the category of the article. You could do something like this:

has_attached_file :image, :default_url => "/public/missing/:category_name.png"

The interpolation would look like this:

Paperclip.interpolates :category_name do |attachment, style|
  attachment.instance.category.name
end

Then, when you call @article.image.url, you'll get "/public/missing/awesome_category.png"

Interpolating access tokens

Note that in Rails 5+, you can do this with the has_secure_token helper that comes with ActiveRecord::Base. Instead of rolling your own token generation method, you can simply add has_secure_token :access_token to any model that has a Paperclip attachment. You still have to add the interpolation to access the access_token column.

I assume that you want to use random access_token in path and it is saved in database.

define attachment

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" }

generate access_token and interpolate it

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