Skip to content
This repository

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

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
Something went wrong with that request. Please try again.