Skip to content

Instantly share code, notes, and snippets.

@nazarhussain
Created June 22, 2011 13:29
Show Gist options
  • Save nazarhussain/1040091 to your computer and use it in GitHub Desktop.
Save nazarhussain/1040091 to your computer and use it in GitHub Desktop.
Enable conditional default_url for Paperclip, to set default url with some method in the model
In some cases you need to set the default_url of paper clip base on some condition. e.g. You want to set default image on basis of gender of user. For this purpose this gist can make it possible to use a method as default_url. Just copy paper_clip_default_url_fix.rb to initializers folder, and use default_url as mentioned in model.rb
class User < ActiveRecord::Base
def set_picture_respect_to_gender
self.gender? ? '/images/male.jpg' : '/images/female.jpg'
end
has_attached_file :display_picture,
:styles => { :medium => "150x150>", :thumb => "100x100>", :small => "50x50>" },
:url => "/system/user/:id/:attachment/:style/:basename.:extension"
:default_url => :set_picture_respect_to_gender
end
module Paperclip
module Interpolations
def self.interpolate pattern, *args
if pattern.kind_of? Symbol
args.first.instance.send(pattern)
else
all.reverse.inject( pattern.dup ) do |result, tag|
result.gsub(/:#{tag}/) do |match|
send( tag, *args )
end
end
end
end
end
end
@AvaelKross
Copy link

I know it's outdated as hell, but if anyone is still here - BE CAREFUL WITH THIS CODE! It slows down the code A LOT, especially if you need to get many image urls on the same page.

@nazarhussain
Copy link
Author

@AvaelKross Yes its about 8 year old code and I am not sure if its valid any more. But for clarity reasons can you pin-point exactly what code slows down? It slows down the startup or a request cycle?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment